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
.
Hide TagsLinked List Pointers This problem is a bit difficult to understand, K means that the list right from the first K, K is greater than the number of chains when the loop read, so the title K =5 when the direct return. The idea is to determine where the list is broken, there is a technique is a fast pointer to go through the K-times, and then the speed of the pointer once again, if the fast pointer to the tail, the slow pointer after the fast pointer k times, just right up the K step.
1#include <iostream>2 using namespacestd;3 4 /**5 * Definition for singly-linked list.6 */7 structListNode {8 intVal;9ListNode *Next;TenListNode (intx): Val (x), Next (NULL) {} One }; A - classSolution { - Public: theListNode *rotateright (ListNode *head,intk) { - if(head==null| | k==0)returnhead; - intCNT =0; -ListNode * first=head,*slow=head; + while(cnt<k) { - if(first==null) First =head; +First=first->Next; Acnt++; at } - if(First==null)returnhead; - while(first->next!=NULL) { -First=first->Next; -Slow=slow->Next; - } infirst->next=head; -Head = slow->Next; toSlow->next =NULL; + returnhead; - } the }; * $ intMain ()Panax Notoginseng { - the return 0; +}
View Code
[Leetcode] Rotate list single-Necklace table rotation