Skip to content

Commit c078a7f

Browse files
Merge pull request #17 from zouyingjie/master
001 号第一周作业: LeetCode24-Swap Nodes in Pairs
2 parents b39afcb + 6083701 commit c078a7f

File tree

2 files changed

+119
-0
lines changed

2 files changed

+119
-0
lines changed

Week_01/id_1/LeetCode24.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
3+
ListNode prePairTail = null;
4+
5+
public ListNode swapPairs(ListNode head) {
6+
7+
if (head == null) {
8+
return null;
9+
}
10+
11+
if (head.next == null) {
12+
return head;
13+
}
14+
15+
ListNode result = head.next;
16+
17+
ListNode node = head;
18+
ListNode next = head.next;
19+
while (node != null && next != null) {
20+
21+
node = swap(node, next);
22+
23+
if (node == null) {
24+
break;
25+
}
26+
next = node.next;
27+
}
28+
return result;
29+
30+
}
31+
32+
private ListNode swap(ListNode node, ListNode next) {
33+
34+
ListNode tmpNext = next.next;
35+
next.next = node;
36+
node.next = tmpNext;
37+
if (prePairTail != null) {
38+
prePairTail.next = next;
39+
}
40+
prePairTail = node;
41+
return tmpNext;
42+
}
43+
44+
}

Week_01/id_1/LeetCode25.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
2+
class Solution {
3+
4+
ListNode preGroupTail = null;
5+
ListNode result = null;
6+
7+
public ListNode reverseKGroup(ListNode head, int k) {
8+
9+
if (head == null || head.next == null || k == 1) {
10+
return head;
11+
}
12+
13+
int index = 1;
14+
ListNode groupHead = head;
15+
ListNode groupTail = head;
16+
17+
while (true) {
18+
19+
if (index != k) { // 查找 k 个节点中的 head 和 tail 节点
20+
groupTail = groupTail.next;
21+
if (groupTail != null) {
22+
index ++;
23+
continue;
24+
}else {
25+
// 链表长度小于 K 的情况
26+
if (this.preGroupTail != null) {
27+
this.preGroupTail.next = groupHead;
28+
break;
29+
}else {
30+
return head;
31+
}
32+
}
33+
}else {
34+
// 个数达到 k 时执行交换,返回下一组的 head 节点
35+
ListNode node = this.swap(groupHead, groupTail);
36+
if (node == null) {
37+
break;
38+
}
39+
groupHead = node;
40+
groupTail = node;
41+
index = 1;
42+
}
43+
}
44+
return result;
45+
}
46+
47+
private ListNode swap(ListNode head, ListNode tail) {
48+
49+
// 反转链表
50+
ListNode preNode = null;
51+
ListNode currentNode = head;
52+
while (currentNode != tail) {
53+
ListNode next = currentNode.next;
54+
currentNode.next = preNode;
55+
preNode = currentNode;
56+
currentNode = next;
57+
}
58+
59+
// 当前组的 tail 节点执行 swap
60+
ListNode node= currentNode.next;
61+
currentNode.next = preNode;
62+
63+
// 反转完成,将上一组的 tail 节点指向当前组的 head 节点
64+
// 第一次反转时上一组 tail 为 null,因此要执行判空操作
65+
if (this.preGroupTail != null) {
66+
this.preGroupTail.next = currentNode;
67+
}else {
68+
// 上一组的 tail 为空说明是第一组执行交换
69+
// 结果一定是第一组交换后的 head 节点
70+
result = currentNode;
71+
}
72+
this.preGroupTail = head;
73+
return node;
74+
}
75+
}

0 commit comments

Comments
 (0)