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 .
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {//The subject is very easy to make mistakes!! //there is an implied condition, when the K value is greater than the length of the list, you need to take the mold, and according to the results of the flip, so must first find out the length of the linked list//two methods of solving the subject://Solution One: To find the length of the chain table, Update K, and then use the double pointer, a fast and slow, found to split the point, the list is divided into two. //Note A problem, the newly found K if equal to 0, the representative does not need to flip, directly return can//solution Two: In the chain table length, only need to traverse to the tail node, and the tail node and the head nodes are connected,//the rest of the task only needs a pointer, find the split node, the next position of the node null, return the node's original next can /*Solution One: if (head==null| | k==0) return head; int len=0; ListNode Temp=head; while (temp!=null) {temp=temp.next; len++; } int Dis=k%len; if (dis==0) return head;/////ListNode fast=head; ListNode Slow=head; Temp=head; while (dis>0) {fast=fast.next; dis--; } while (Fast.next!=null) {fast=fast.next; Slow=slow.next; } Temp=slow.next; Slow.next=null; Fast.next=head; return temp;*/ if(head==NULL|| k==0)returnHead; intLen=1; ListNode Temp=Head; while(temp.next!=NULL) {len++; Temp=Temp.next; } Temp.next=Head; intdis=len-k%Len; while(dis>0) {Temp=Temp.next; Dis--; } head=Temp.next; Temp.next=NULL; returnHead; }}
[Leedcode 61] Rotate List