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
.
Solution:
Tips:
calculate the length of the list, and let k mod n to get a useful k. then use two points to record the Kth element from right to left. then cut it and re-link it.
Java Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
ListNode p = head;
int n = 0;
// calculate the length of the list
while (p != null) {
n++;
p = p.next;
}
// mod n to get a useful value
k = k % n;
n = k;
if (k == 0) {
return head;
}
// locate to the Kth element
p = head;
ListNode q = head;
while (p.next != null) {
p = p.next;
if (--n < 0) {
q = q.next;
}
}
// rotate
p.next = head;
head = q.next;
q.next = null;
return head;
}
}