这个更简单,用双指针没发直接处理,因为快指针的位置要在慢指针前面n-k的位置,但是链表多长是不知道的。如果需要先遍历一次获取长度,再来一次,不如用n保存了
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* creatList(void)
{
ListNode* node5 = new ListNode(5);
ListNode* node4 = new ListNode(4, node5);
ListNode* node3 = new ListNode(3, node4);
ListNode* node2 = new ListNode(2, node3);
ListNode* node1 = new ListNode(1, node2);
return node1;
}
void printList(ListNode* node)
{
while(nullptr != node)
{
cout<<node->val<<",";
node = node->next;
}
cout<<endl;
}
ListNode* rotateRight(ListNode* node, int k) {
int n=0;
ListNode head = ListNode(-1, node);
auto tail = &head;
while(nullptr != tail->next)
{
++n;
tail = tail->next;
}
tail->next = head.next;
if(0==n)
return nullptr;
k = k % n;
n-=k;
node = &head;
while(n>0)
{
--n;
node = node->next;
}
head.next = node->next;
node->next = nullptr;
return head.next;
}
int main(void)
{
printList(rotateRight(nullptr, 0));
return 0;
}