-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList.java
More file actions
64 lines (51 loc) · 1.16 KB
/
RotateList.java
File metadata and controls
64 lines (51 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package leetcode;
import org.junit.Test;
import junit.framework.TestCase;
/**
* Link: https://leetcode.com/problems/rotate-list/
*
* @author shivam.maharshi
*/
public class RotateList extends TestCase {
@Test
public static void test() {
ListNode o = new ListNode(1);
ListNode t = new ListNode(2);
ListNode th = new ListNode(3);
ListNode f = new ListNode(4);
ListNode fi = new ListNode(5);
o.next = t;
t.next = th;
th.next = f;
f.next = fi;
// assertEquals(f, rotateRight(o, 2));
assertEquals(f, rotateRight(o, 7));
}
public static ListNode rotateRight(ListNode head, int k) {
if (head == null)
return head;
int l = 0;
ListNode n = head;
while (n != null) {
n = n.next;
l++;
}
if (k % l == 0)
return head;
k = l - (k % l);
ListNode first = head;
ListNode last = null;
while (k > 0) {
last = first;
first = first.next;
k--;
}
ListNode t = first;
while (t.next != null) {
t = t.next;
}
t.next = head;
last.next = null;
return first;
}
}