Reorder List
https://leetcode.com/problems/reorder-list/description/
Thoughts
单指针列表顺序变为 L0→Ln→L1→Ln-1→L2→Ln-2→…。把后一半反转,再从head开始隔一个插一个。找中点用快慢指针,再配合dummy和i,j指针方便做merge list。
Code
/*
* @lc app=leetcode id=143 lang=cpp
*
* [143] Reorder List
*/
// @lc code=start
/**
* 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) return;
ListNode *dummy = new ListNode(-1), *fast = head->next, *slow = head, *cur = head, *i, *j;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
fast = fast->next;
}
cur = slow->next;
slow->next = nullptr;
ListNode *pre = nullptr;
while (cur != nullptr) {
auto next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
i = head;
j = pre;
cur = dummy;
while (i != nullptr && j != nullptr) {
cur->next = i;
i = i->next;
cur->next->next = j;
cur = j;
j = j->next;
}
cur->next = i;
}
};
// @lc code=end
Analysis
TC: O(n), SC: O(1).
Last updated
Was this helpful?