https://oj.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 must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
<pre name="code" class="cpp">class Solution {
public:
void reorderList(ListNode *head) {
if (head == NULL || head->next == NULL || head->next->next == NULL) {
return;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* mid = slow->next;
slow->next = NULL;
ListNode *secondHead = reverseList(mid);
mergeList(head, secondHead);
}
private:
ListNode *reverseList(ListNode *head) {
ListNode *pCur = head;
ListNode *pTemp = head->next;
ListNode *pPrev = NULL;
pCur->next = NULL;
while (pTemp != NULL) {
pPrev = pTemp;
pTemp = pTemp->next;
pPrev->next = pCur;
pCur = pPrev;
}
return pCur;
}
void mergeList(ListNode *first, ListNode *second) {
ListNode *newListCur = first;
ListNode *firstCur = first->next;
ListNode *secondCur = second;
ListNode *firstNext = NULL;
ListNode *secondNext = NULL;
while (secondCur != NULL) {
firstNext = firstCur->next;
secondNext = secondCur->next;
newListCur->next = secondCur;
secondCur->next = firstCur;
newListCur = firstCur;
firstCur = firstNext;
secondCur = secondNext;
}
}
};