Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 12e58d6

Browse files
add q25_k个一组翻转链表
1 parent 4be6716 commit 12e58d6

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
* [q2_两数相加](/src/链表操作/q2_两数相加)
1212
* [q19_删除链表的倒数第N个节点](/src/链表操作/q19_删除链表的倒数第N个节点)
13+
* [q25_k个一组翻转链表](/src/链表操作/q25_k个一组翻转链表)
1314
* [q61_旋转链表](/src/链表操作/q61_旋转链表)
1415
* [q138_复制带随机指针的链表](/src/链表操作/q138_复制带随机指针的链表)
1516
* [q206_反转链表](/src/链表操作/q206_反转链表)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package 链表操作.q25_k个一组翻转链表;
2+
3+
4+
public class ListNode {
5+
int val;
6+
ListNode next;
7+
8+
ListNode(int x) {
9+
val = x;
10+
}
11+
}
12+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package 链表操作.q25_k个一组翻转链表;
2+
3+
public class Solution {
4+
5+
public ListNode reverseKGroup(ListNode head, int k) {
6+
ListNode hair = new ListNode(0);
7+
hair.next = head;
8+
9+
ListNode pre = hair;
10+
ListNode end = hair;
11+
12+
while (end.next != null) {
13+
for (int i = 0; i < k && end != null; i++){
14+
end = end.next;
15+
}
16+
if (end == null){
17+
break;
18+
}
19+
ListNode start = pre.next;
20+
ListNode next = end.next;
21+
end.next = null;
22+
pre.next = reverse(start);
23+
start.next = next;
24+
pre = start;
25+
26+
end = pre;
27+
}
28+
return hair.next;
29+
}
30+
31+
private ListNode reverse(ListNode head) {
32+
ListNode pre = null;
33+
ListNode curr = head;
34+
while (curr != null) {
35+
ListNode next = curr.next;
36+
curr.next = pre;
37+
pre = curr;
38+
curr = next;
39+
}
40+
return pre;
41+
}
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /