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 .
The problem is not difficult, that is, to give a number k, and then from right to left number K node, and then start with this node, re-form a linked list.
It is important to note that if K is greater than the list length len, then k = K%len
The trick is that when you k<len, you can count the number of K from front to back, and then walk backwards from the current position (flag) and head to the end, which is a bit more efficient.
But the first time is not very fast, time consuming 15ms.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {if(k = = 0 | | head = =NULL){ returnHead; } ListNode Flag=Head; intLen; for(len = 1;len < K && Flag.next! =NULL; len++) {flag=Flag.next; } if(len = =k) { if(Flag.next = =NULL) returnHead; ListNode result=Head; Flag=Flag.next; while(Flag.next! =NULL) {result=Result.next; Flag=Flag.next; } Flag.next=Head; Flag=Result.next; Result.next=NULL; returnFlag; } ListNode Last=Flag; if(k >Len) k= len-k%Len; Elsek= len-K; if(k = = 0 | | k = =len)returnHead; Flag=Head; for(inti = 1;i<k; i++) {flag=Flag.next; } Last.next=Head; Head=Flag.next; Flag.next=NULL; returnHead; }}
Then looked at the online 1ms answer, in fact, there is no difference, and then take their run, the results of 15, 16ms, so the Leetcode site itself (perhaps a Java Virtual machine) problem.
Leetcode Rotate List-----java