描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
中文:将链表重新排序,一个是升序,一个是降序。
分析:
思路就是:
1 用快慢指针找到中间节点
2 翻转中间节点后一个元素到最后一个元素区间的所有元素
3 断开前半段和翻转后的后半段元素
4 把前半段和翻转后的后半段元素以交叉的方式合并起来
5 特殊处理输入为空,只有一个元素和只有两个元素的corner case,就是多加几个if…return
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return;
ListNode *slow = head, *fast = head, *prev = nullptr;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = nullptr; // cut at middle
slow = reverse(slow);
// merge two lists
ListNode *curr = head;
while (curr->next) {
ListNode *tmp = curr->next;
curr->next = slow;
slow = slow->next;
curr->next->next = tmp;
curr = tmp;
}
curr->next = slow;
}
ListNode* reverse(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *prev = head;
for (ListNode *curr = head->next, *next = curr->next; curr;
prev = curr, curr = next, next = next ? next->next : nullptr) {
curr->next = prev;
}
head->next = nullptr;
return prev;
}
};
364

被折叠的 条评论
为什么被折叠?



