LeetCode 143. 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}.

解题思路:
这是一个很常规的题目, 拿到这道题目只需要将链表分割成前后两段,可以借助快慢指针的做法, 然后将后面一个链表逆置, 再按照指定的次序排序就可以了

下面是代码:

/**
 * 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) {
        // 先找到链表的中心位置, 切开
        ListNode myhead(0);
        myhead.next = head;
        ListNode * p1 = &myhead, *p2 = &myhead;
        while (p1 && p1->next){
            p1 = p1->next->next;
            p2 = p2->next;
        }
        ListNode * pNext = p2->next;

        // 将后面一部分链表切开
        ListNode myhead2(0);
        p2->next = nullptr;
        myhead2.next = pNext;

        // 将链表2 逆置
        ListNode * pCur = myhead2.next;
        ListNode * pPre = nullptr;
        while (pCur){
            ListNode * pNext = pCur->next;
            pCur->next = pPre;
            pPre = pCur;
            pCur = pNext;
        }
        myhead2.next = pPre;

        // 归并排序, 因为p1 >= p2
        p1 = myhead.next;
        p2 = myhead2.next;
        ListNode res(0);
        ListNode * pres = &res;
        while (p1){
            pres->next = p1;
            p1 = p1->next;
            pres = pres->next;
            pres->next = nullptr;

            if (p2){
                pres->next = p2;
                p2 = p2->next;
                pres = pres->next;
                pres->next = nullptr;
            }
        }
    }
};

你可能感兴趣的:(LeetCode)