Topic:
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 .
Category: LinkedList twopointers
Code: Key constructs a ring and then disconnects from the corresponding position
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Rotateright (listnode* head,intk) { A if(!head) - returnhead; - intLength =1; theListNode *newhead, *tail; -Newhead = Tail =head; - //Get knot points - while(tail->next) + { -Tail = tail->Next; +length++; A } at //Constructs a change -Tail->next =head; - - if(k%=length) - { - for(inti =0; i < length-k; ++i) inTail = tail->Next; - } toNewhead = tail->Next; +Tail->next =NULL; - returnNewhead; the } *};
[LeetCode61] Rotate List