Skip to content

Commit 921d400

Browse files
author
houfachao
committed
25. K 个一组翻转链表
1 parent 1e16881 commit 921d400

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.geekidentity.leetcode.n0025;
2+
3+
public class ReverseKGroup {
4+
public ListNode reverseKGroup(ListNode head, int k) {
5+
if (head == null || head.next == null) return head;
6+
ListNode dummy = new ListNode(0, head);
7+
ListNode pre = dummy, end = dummy;
8+
while (end.next != null) {
9+
for (int i = 0; i < k && end != null; i ++) {
10+
end = end.next;
11+
}
12+
if (end == null) break;;
13+
ListNode start = pre.next;
14+
ListNode next = end.next;
15+
end.next = null;
16+
ListNode newHead = reverse(start);
17+
pre.next = newHead;
18+
start.next = next;
19+
pre = start;
20+
end = pre;
21+
}
22+
return dummy.next;
23+
24+
}
25+
26+
public ListNode reverse(ListNode head) {
27+
if (head == null || head.next == null) return head;
28+
ListNode pre = null, cur = head, next = null;
29+
while (cur != null) {
30+
next = cur.next;
31+
cur.next = pre;
32+
pre = cur;
33+
cur = next;
34+
}
35+
return pre;
36+
}
37+
38+
static class ListNode {
39+
int val;
40+
ListNode next;
41+
ListNode() {}
42+
ListNode(int val) { this.val = val; }
43+
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
44+
}
45+
}

0 commit comments

Comments
 (0)