LeetCode::Reorder List

来源:互联网 发布:看图编辑软件 编辑:程序博客网 时间:2024/05/16 14:17

https://oj.leetcode.com/problems/reorder-list/

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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;        }    }};







0 0
原创粉丝点击