题目描述:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
思路:注释即思路。
#include<cstdio>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* rotateRight(ListNode* head, int k)
{
int size = 0;
ListNode* start = head;
ListNode* end = head;
//如果没有节点或只有一个节点不做任何处理
if(head==NULL)
return NULL;
if(head->next==NULL)
return head;
//计算链表长度
while(end->next->next!=NULL)
{
size++;
end = end->next;
}
//end指针停在倒数第二个节点,并没有将最后两个节点算上
size += 2;
k %= size;
int count = 0;
ListNode* mid = head;
//如果说操作次数正好是一个循环,那么就等于不变动链表,那么不做任何处理
while(k>0&&count!=k)
{
int n = 0;
//经过一次对链表长度的查询,end已经停在了倒数第二个节点上,第一次不需要end指针找位置
if(count!=0)
{
while(n<size-2)
{
n++;
end = end->next;
}
}
mid = end->next;
end->next = NULL;
mid->next = start;
start = mid;
end = start;
count++;
}
head = start;
return head;
}
int main(){
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
ListNode* node4 = new ListNode(4);
ListNode* node5 = new ListNode(5);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
int k = 2;
ListNode* result = rotateRight(head,k);
while(result!=NULL)
{
printf("%d",result->val);
if(result->next!=NULL)
printf("->");
result = result->next;
}
return 0;
}