-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode025.java
87 lines (72 loc) · 1.49 KB
/
Leetcode025.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package test;
//关键在反转单链表
public class Leetcode025 {
ListNode test;
ListNode start;
ListNode end;
ListNode pcur;
//判断是否能够反转
public boolean isKMembers(ListNode head, int k) {
test = head;
int i = 0;
while (i < k) {
if (test != null) {
i++;
test = test.next;
continue;
}
return false;
}
return true;
}
//反转单链表,因为java没有头结点,定义pre为前一项
public ListNode reverse(ListNode pre, int n) {
start = pre.next;
end = start;
pcur = start.next;
for (int i=1; i<n; i++) {
end.next = pcur.next;
pcur.next = start;
pre.next = pcur;
start = pcur;
pcur = end.next;
}
return start;
}
//给定假头结点tail,迭代指向每次反转后最后一项
public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
ListNode tail = new ListNode(0);
tail.next = head;
int i = 0;
while (isKMembers(cur, k)) {
if (i == 0) {
head = reverse(tail, k);
tail = end;
}
else {
tail.next = reverse(tail, k);
tail = end;
}
i++;
cur = tail.next;
}
return head;
}
public static void main(String args[]) {
int[] nums = {1, 2, 3, 4, 5};
ListNode head = new ListNode(nums[0]);
ListNode cur = head;
for (int i=1; i<nums.length; i++) {
cur.next = new ListNode(nums[i]);
cur = cur.next;
}
int k = 2;
Leetcode025 test = new Leetcode025();
head = test.reverseKGroup(head, k);
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
}