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个节点的那道题差不多,都是用fast和slow指针得到相应的位置,这道题需要注意一下k大于链表长度的情况。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || k == 0) return head;
ListNode prehead(0);
prehead.next = head;
ListNode *p = head,*fast = head,*slow = &prehead;
int len = 1;
while(p->next != NULL)
{
if(len++ == k) fast = p;
p = p->next;
}
if(len == 1 || k%len == 0) return head;
if(len <= k) {
p = head;
k %= len;
int i = 1;
while(p->next != NULL)
{
if(i++ == k) fast = p;
p = p->next;
}
}
while(fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
fast->next = head;
head = slow->next;
slow->next = NULL;
return head;
}
};
52 milli secs