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
The idea is to get the whole length of the list, get the rotate position.
cut the list from the rotate position, and link the front part and back part.
c++
ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || k == 0) return head; ListNode *p=head; int len = 1; while(p->next != NULL){ p = p->next; len++; } p->next = head; int dis = len - k%len; while(dis !=0){ p = p->next; dis--; } head = p->next; p->next = NULL; return head; }
java
public ListNode rotateRight(ListNode head, int n) { if(head == null || n==0) return head; ListNode p = head; int len = 1; while(p.next!=null){ len++; p = p.next; } p.next = head; int dis = len - n%len; while(dis>0){ p = p.next; dis--; } head = p.next; p.next = null; return head; }