Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
思路: 循环右移k位
1)获取链表的长度
2)移动到第(list.size()-k%list.size())位
3)链接:将链表的尾节点指向链表的首节点,并将指向第(list.size()-k%list.size())位的节点的后继节点置NULL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head==NULL||head->next==NULL)
return head;
int num=1;
ListNode *cur=head;
while(cur->next!=NULL)
{
num++;
cur=cur->next;
} //链表的长度num
k=num-(k%num);// 链表的第k个节点是返回的链表的首节点
ListNode * pre=head;
cur->next=head;
while(k>0)//找到第k个的节点
{
pre=pre->next;
k--;
}
while(cur->next!=pre)//找到第k个节点前节点
{
cur=cur->next;
}
cur->next=NULL;
return pre;
}
};