LeetCode-M-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:
    ListNode* reverseList(ListNode* head){
        if(head == NULL || head->next == NULL) return head;
        ListNode* cur = head;
        while(cur->next != NULL){
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = head;
            head = next;
        }
        return head;
    }
    void reorderList(ListNode* head) {
        if(head == NULL || head->next == NULL) return;
        //slow and fast pointer
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* pre = NULL;
        while(fast != NULL && fast->next != NULL){
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        ListNode* rhead = reverseList(slow);
        ListNode* pcur = head;
        ListNode* qcur = rhead;
        ListNode* tail = head;
        while(qcur != NULL && pcur != NULL){
            ListNode * qnext = qcur->next;
            qcur->next = pcur->next;
            pcur->next = qcur;
            pcur = qcur->next;
            if(pcur != NULL) tail = pcur;
            else tail = qcur;
            qcur = qnext;
        }
        if(qcur != NULL) tail->next = qcur;
        return;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章