Given the head
of a linked list, rotate the list to the right by k
places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]
- The number of nodes in the list is in the range
[0, 500]
. - -100 <= Node.val <= 100
- 0 <= k <= 2 * 109
public ListNode rotateRight(ListNode head, int k) {
if (head == null)
return null;
int size = 0;
ListNode temp = head,
newHead = null,
p1 = head,
p2 = head;
while (temp != null) {
size++;
temp = temp.next;
}
k %= size;
for (int i = 0; i < k; i++)
p2 = p2.next;
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
p2.next = head;
newHead = p1.next;
p1.next = null;
return newHead;
}