Skip to content

Commit 13ce25b

Browse files
committed
Rotate List
1 parent c00c4cf commit 13ce25b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

RotateList.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Given a list, rotate the list to the right by k places, where k is
3+
* non-negative.
4+
*
5+
* For example:
6+
*
7+
* Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
8+
*
9+
*/
10+
11+
public class RotateList {
12+
public ListNode rotateRight(ListNode head, int n) {
13+
if (head == null)
14+
return head;
15+
int length = 1;
16+
ListNode last = head;
17+
while (last.next != null) {
18+
last = last.next;
19+
length++;
20+
}
21+
n = n % length;
22+
if (n == 0)
23+
return head;
24+
int steps = length - n;
25+
ListNode start = new ListNode(0);
26+
start.next = head;
27+
while (steps > 0) {
28+
start = start.next;
29+
steps--;
30+
}
31+
ListNode ret = start.next;
32+
start.next = null;
33+
last.next = head;
34+
return ret;
35+
}
36+
}

0 commit comments

Comments
 (0)