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
.
Analysis:
1. Compute the length of list m
2. partition list into the small list, notice that it moves exactly to the end of the list, and the next is null!!
Before list is List1, after list was list2, set last node in list1 List1.next = null
3. Concatenate the tail of the list to the head of one list
Java Code
20160601
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {//1. Compute the length of list m//2. Partition list into the small list,//before list is List1, after list was list2, set last node in list1 list1.next = null//3. Concatenate the tail of the list to the head of one list//Base Case if(Head = =NULL|| Head.next = =NULL|| K = = 0) { returnHead; } intm =GetLength (head); intMovestep = m-k% m-1; ListNode cur=Head; ListNode One=Head; ListNode=NULL; while(Movestep > 0) {cur=Cur.next; Movestep--; } if(Cur.next = =NULL) {//move to the end of the linked list, no rotate returnHead; }=Cur.next; Cur.next=NULL; ListNode Twohead=both ; while(Two.next! =NULL) {=Two.next; } Two.next=One ; returnTwohead; } Private intGetLength (ListNode head) {intLen = 0; while(Head! =NULL) {Head=Head.next; Len++; } returnLen; }}
Leetcode 61. Rotate List