这道题是链表逆置的升级版。
#include<iostream>
#include<assert.h>
using namespace std;
struct Node
{
int _data;
Node* _next;
Node(const int& x)
: _data(x)
, _next(NULL)
{}
};
Node* Reverse(Node* head, Node* tail)
{
assert(head);
Node* cur = head;
Node* prev = NULL;
Node* next = NULL;
Node* ReversedHead;
if (head == NULL)
return NULL;
if (head->_next == NULL)
return head;
while (cur != tail)
{
next = cur->_next;
cur->_next = prev;
prev = cur;
cur = next;
}
ReversedHead = prev;
return ReversedHead;
}
Node* RotateList(Node* list, size_t k)
{
assert(list);
int count = 0;
int index = 0;
Node* cur = list->_next;
Node* head = list;
Node* tail = list;
Node* prev = list;
Node* RotataHead = NULL;
Node* RotataTail = NULL;
Node* RotataList = NULL;
for (int i = 0; i < k; ++i)
{
tail = tail->_next;
if (tail == NULL)
break;
}
RotataList = Reverse(head, tail);//翻转前k个节点
RotataTail = head;
head = tail;
while (tail)
{
tail = tail->_next;
index++;
if (head&&index%k == 0)
{
RotataHead = Reverse(head, tail);
RotataTail->_next = RotataHead;
RotataTail = head;
head = tail;
}
}
if (head)
{
RotataTail->_next = head;
}
return RotataList;
}
int main()
{
Node* p1 = new Node(1);
Node* p2 = new Node(2);
Node* p3 = new Node(3);
Node* p4 = new Node(4);
Node* p5 = new Node(5);
Node* p6 = new Node(6);
p1->_next = p2;
p2->_next = p3;
p3->_next = p4;
p4->_next = p5;
p5->_next = p6;
//Node* p = RotateList(p1, 2);
Node* p = RotateList(p1, 5);
return 0;
}

本文介绍了一种链表操作算法——链表旋转。该算法通过多次局部逆置来实现链表中元素位置的整体调整,每一步逆置k个节点,直至完成整个链表的旋转。文章提供了完整的C++代码实现,并通过实例演示了算法的具体应用。

被折叠的 条评论
为什么被折叠?



