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

思路:將鏈表從中間斷開成前後兩部分,將前後兩部分交叉合併

/**
 * 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==NULL || head->next==NULL)
            return;
        
        ListNode* slow=head;
        ListNode* fast=head;
        
        //定位鏈表中間
        while(fast->next!=NULL && fast->next->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        
        ListNode* sHead=slow->next;
        slow->next = NULL;//斷開前後兩部分
        reverList(&sHead);
        print(sHead);
        mergeList(head, sHead);
    }
private:
    void print(ListNode* head)
    {
        while(head)
        {
            cout<<head->val<<" ";
            head=head->next;
        }
        cout<<endl;
    }
    //一定要傳遞指針的指針,因爲要修改傳入的指針
    void reverList(ListNode** pphead)
    {
        ListNode *head = *pphead;       // -----------------1
        if(head==NULL || head->next==NULL)
            return;
            
        ListNode* rHead = head ;
        head=head->next;
        rHead->next=NULL;
        while(head)
        {
            ListNode* tmp = head->next;
            head->next = rHead;         //  ----------------2
            rHead=head;
            head=tmp;
        }
        *pphead=rHead;  // 一定要有這一句,不能因爲1,2兩句就覺得修改,head是個指針,*pphead的臨時拷貝副本 (ListNode *head = *pphead),修改head指針的指向,只是修改了臨時拷貝副本的指向,並沒有修改*pphead本身的指向
    }
    void mergeList(ListNode* fHead, ListNode* sHead)
    {
        if(fHead==NULL || sHead==NULL)
            return;
        while(sHead)
        {
            ListNode* tmp = fHead->next;
            fHead->next = sHead;
            sHead=sHead->next;  // 一定要寫在這裏,fHead->next->next=tmp; 的前面,不能寫在3的位置,因爲下一句修改了sHead->next
            fHead->next->next=tmp;
            
            //sHead=sHead->next;    //  ------------------3
            fHead=tmp;
        }
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章