C++ 将单链表的每K个结点逆序

来源:互联网 发布:朱少民 软件测试 视频 编辑:程序博客网 时间:2024/06/09 14:47
#include <iostream>
#include <stack>


struct Node {
int value;
Node *next;
Node(int data) : value(data), next(nullptr) {};
};


Node * reverseKNodes(Node * head, int k);
Node * reConnected(std::stack<Node *> &stack, Node * left, Node * right);
void print(const Node * head);


int main()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
Node n6(6);
Node n7(7);
Node n8(8);


n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = &n8;


print(reverseKNodes(&n1, 3));




system("pause");
return 0;
}


void print(const Node * head)
{
while (head != nullptr) {
std::cout << head->value << std::endl;
head = head->next;
}
}


Node * reverseKNodes(Node * head, int k)
{
if (head == nullptr || k < 2) {
return head;
}


Node *left    = nullptr;
Node *right   = nullptr;
Node *cur     = head;
Node *newHead = head;
std::stack<Node *> stk;


while (cur != nullptr)
{
stk.push(cur);
right = cur->next;
if (stk.size() == k) {
left = reConnected(stk, left, right);
newHead = newHead == head ? cur : newHead;//保存新的头
}
cur = right;
}
return newHead;
}


Node * reConnected(std::stack<Node *> &stack, Node * left, Node * right)
{
Node *cur = stack.top();
stack.pop();
if (left != nullptr) {//如果是传入的第一组 则不需要连接左边结点
left->next = cur;
}
while (!stack.empty()) {//栈不空,依次连接栈中的结点
cur->next = stack.top();
cur = stack.top();
stack.pop();
}
cur->next = right;//栈中元素连接完成后,将栈中最后一个结点与原链表的下一个结点连接
return cur;
}