0%

Rotate List

Question

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ListNode rotateRight(ListNode head, int k) {
if ( head == null || head.next == null ) return head;

ListNode tmp = head;
int l = 1;
while (tmp.next != null) {
tmp = tmp.next;
l++;
}

tmp.next = head;
for (k = l-k%l; k > 0; k--)
tmp = tmp.next;
head = tmp.next;
tmp.next = null;
return head;
}