Skip to content

001 号第一周作业: LeetCode24-Swap Nodes in Pairs #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Week_01/id_1/LeetCode24.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {

ListNode prePairTail = null;

public ListNode swapPairs(ListNode head) {

if (head == null) {
return null;
}

if (head.next == null) {
return head;
}

ListNode result = head.next;

ListNode node = head;
ListNode next = head.next;
while (node != null && next != null) {

node = swap(node, next);

if (node == null) {
break;
}
next = node.next;
}
return result;

}

private ListNode swap(ListNode node, ListNode next) {

ListNode tmpNext = next.next;
next.next = node;
node.next = tmpNext;
if (prePairTail != null) {
prePairTail.next = next;
}
prePairTail = node;
return tmpNext;
}

}
75 changes: 75 additions & 0 deletions Week_01/id_1/LeetCode25.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@

class Solution {

ListNode preGroupTail = null;
ListNode result = null;

public ListNode reverseKGroup(ListNode head, int k) {

if (head == null || head.next == null || k == 1) {
return head;
}

int index = 1;
ListNode groupHead = head;
ListNode groupTail = head;

while (true) {

if (index != k) { // 查找 k 个节点中的 head 和 tail 节点
groupTail = groupTail.next;
if (groupTail != null) {
index ++;
continue;
}else {
// 链表长度小于 K 的情况
if (this.preGroupTail != null) {
this.preGroupTail.next = groupHead;
break;
}else {
return head;
}
}
}else {
// 个数达到 k 时执行交换,返回下一组的 head 节点
ListNode node = this.swap(groupHead, groupTail);
if (node == null) {
break;
}
groupHead = node;
groupTail = node;
index = 1;
}
}
return result;
}

private ListNode swap(ListNode head, ListNode tail) {

// 反转链表
ListNode preNode = null;
ListNode currentNode = head;
while (currentNode != tail) {
ListNode next = currentNode.next;
currentNode.next = preNode;
preNode = currentNode;
currentNode = next;
}

// 当前组的 tail 节点执行 swap
ListNode node= currentNode.next;
currentNode.next = preNode;

// 反转完成,将上一组的 tail 节点指向当前组的 head 节点
// 第一次反转时上一组 tail 为 null,因此要执行判空操作
if (this.preGroupTail != null) {
this.preGroupTail.next = currentNode;
}else {
// 上一组的 tail 为空说明是第一组执行交换
// 结果一定是第一组交换后的 head 节点
result = currentNode;
}
this.preGroupTail = head;
return node;
}
}