Question
- Given a list, rotate the list to the right by k places, where k is non-negative.
Example
- Given
1->2->3->4->5->NULL
and k = 2
,
- return
4->5->1->2->3->NULL
.
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) {
return head;
}
ListNode anchor = new ListNode(0);
anchor.next = head;
int nodeNumber = getNodeNumber(head);
int step = k % nodeNumber;
ListNode first = head;
ListNode second = head;
while (step > 0) {
second = second.next;
step--;
}
while (second.next != null) {
first = first.next;
second = second.next;
}
second.next = head;
anchor.next = first.next;
first.next = null;
return anchor.next;
}
// calculate the number of node in the linked list
private int getNodeNumber(ListNode head) {
int count = 0;
while (head != null) {
count++;
head = head.next;
}
return count;
}
}