#include "List.h"
#include <stack>
using namespace std;
Node* resign1(stack<Node*> &nstack, Node* left, Node* right)
{
Node* cur = nstack.top();
nstack.pop();
if(left != nullptr)
left->next = cur;
Node* next = nullptr;
while(!nstack.empty())
{
next = nstack.top();
nstack.pop();
cur->next = next;
cur = next;
}
cur->next = right;
return cur;
}
Node* reverseKNode1(Node* head, int k)
{
if(k < 2)
return head;
stack<Node*> nStack;
Node* newHead = head;
Node* cur = head;
Node* pre = nullptr;
Node* next = nullptr;
while(cur)
{
next = cur->next;
nStack.push(cur);
if(nStack.size() == k)
{
pre = resign1(nStack, pre, next);
newHead = newHead == head ? cur : newHead;
}
cur = next;
}
return newHead;
}
void resign2(Node* left, Node* start, Node* end, Node* right)
{
Node* pre = start;
Node* cur = start->next;
Node* next = nullptr;
while(cur != right)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
if(left != nullptr)
left->next = end;
start->next = right;
}
Node* reverseKNode2(Node* head, int k)
{
if(k < 2)
return head;
Node* cur = head;
Node* start = nullptr;
Node* end = nullptr;
Node* pre = nullptr;
Node* next = nullptr;
int count = 1;
while(cur)
{
next = cur->next;
if(count == k)
{
start = pre == nullptr ? head : pre->next;
head = pre == nullptr ? cur : head;
resign2(pre, start, cur, next);
pre = start;
count = 0;
}
++count;
cur = next;
}
return head;
}
int main()
{
Node* pNode0 = new Node(0);
Node* pNode1 = new Node(1, pNode0);
Node* pNode2 = new Node(2, pNode1);
Node* pNode3 = new Node(2, pNode2);
Node* pNode4 = new Node(1, pNode3);
Node* pNode5 = new Node(0, pNode4);
pNode5 = reverseKNode1(pNode5, 3);
Print(pNode5);
cout << "============================" << endl;
pNode5 = reverseKNode2(pNode5, 3);
Print(pNode5);
}
将单链表的每K个节点之间逆序
猜你喜欢
转载自blog.csdn.net/wzc2608/article/details/80682126
今日推荐
周排行