Test instructions
The chain list after the K cut out, splicing to the front, such as 1->2->null into 2->1->null. The number represents the meaning of a paragraph.
Ideas:
K has 3 possibilities, k>n,k<n,k=n. The ideal situation is k<n, this is good operation, and when K>n, K%=n can, and when k=n, no need to operate. The linked list may be empty!
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(k==0|| Head==null)returnhead; - -ListNode *first=head, *second=head, *t=head; the intCnt=0; - while(t) cnt++,t=t->next;//Count -k%=CNT; - + while(k--) first=first->next;//move first to the appropriate location - while(First->next)//two hands at the same time. + { AFirst=first->Next; atSecond=second->Next; - } -first->next=head;//splicing Operation -Head=second->Next; -second->next=NULL; - returnhead; in } -};AC Code
Leetcode Rotate List (linked list operation)