143. Reorder List**
https://leetcode.com/problems/reorder-list/
题目描述
Given a singly linked list L: L0 -> L1 -> … -> Ln-1 -> Ln
,
reorder it to: L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 -> …
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
C++ 实现 1
基本思路:
- 首先找到链表的中点, 将链表分为前半部分 pre 和后半部分 post
- 翻转后半部分 post
- 合并前半部分 pre 以及翻转后的 post
查找链表的中点可以使用快慢指针.
class Solution {
private:
ListNode* reverse(ListNode *head) {
ListNode *prev = nullptr;
while (head) {
auto tmp = head->next;
head->next = prev;
prev = head;
head = tmp;
}
return prev;
}
public:
void reorderList(ListNode* head) {
if (!head || !head->next) return;
// 第一步
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
auto rlist = slow->next;
slow->next = nullptr;
// 第二步
rlist = reverse(rlist);
// 第三步
ListNode *dummy = new ListNode(0);
auto p = dummy;
bool choose = true;
while (head && rlist) {
if (choose) {
p->next = head;
head = head->next;
} else {
p->next = rlist;
rlist = rlist->next;
}
p = p->next;
choose = !choose;
}
p->next = head ? head : rlist;
head = dummy->next;
}
};
C++ 实现 2
下面代码中的 merge
操作值得细细品味. 可以发现 head
指向整条链表, 而 ptr
指向翻转后的后半部分链表, 代码这样写没有问题. 思路有点像: 160. Intersection of Two Linked Lists*.
class Solution {
private:
ListNode* reverse(ListNode *head) {
ListNode *prev = nullptr;
while (head) {
auto tmp = head->next;
head->next = prev;
prev = head;
head = tmp;
}
return prev;
}
void merge(ListNode *l1, ListNode *l2) {
for (auto p1 = l1, p2 = l2; p1; ) {
auto t = p1->next;
p1->next = p2;
p1 = p1->next;
p2 = t;
}
}
public:
void reorderList(ListNode* head) {
if (!head || !head->next)
return;
ListNode *slow = head, *fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
auto ptr = reverse(slow->next);
merge(head, ptr);
}
};