forked from nibnait/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTempTest.java
More file actions
58 lines (43 loc) · 1.2 KB
/
TempTest.java
File metadata and controls
58 lines (43 loc) · 1.2 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
package algorithm_practice;
import common.datastruct.ListNode;
import common.util.ConstructListNode;
import common.util.SysOut;
import org.junit.Test;
/**
* Created by nibnait on 2020/11/24
*/
public class TempTest {
@Test
public void testCase() {
ListNode head = ConstructListNode.construct(new int[]{1, 2, 3, 4, 5});
SysOut.printList(head);
head = reverseK(head, 2);
SysOut.printList(head);
}
private ListNode reverseK(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode dummyHead = new ListNode();
dummyHead.next = head;
while (dummyHead.next != null) {
dummyHead.next = reverseN(dummyHead.next, k);
for (int i = 0; i < k; i++) {
if (dummyHead.next == null) {
break;
}
dummyHead = dummyHead.next;
}
}
return dummyHead.next;
}
private ListNode reverseN(ListNode head, int n) {
if (n == 1) {
return head;
}
ListNode last = reverseN(head.next, n-1);
head.next.next = head;
head.next = null;
return last;
}
}