/*
* @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
TC: O(n), SC: O(1).