LeetCode 143. Reorder List

Given a singly linked list L: L0L1→…→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}.


Inverse the second half and merge two linked lists.

 ListNode* reverse(ListNode* tmp) {
        if(!tmp || !tmp->next) return tmp;
        ListNode* dummy = NULL;
        while(tmp) {
            ListNode* next  = tmp->next;
            tmp->next = dummy;
            dummy = tmp;
            tmp = next;
        }
        return dummy;
    }
    
    void reorderList(ListNode* head) {
        if(!head || !head->next || !head->next->next) return;
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next && fast->next->next) {   // get the middle pointer
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode* tmp1 = head;
        ListNode* tmp2 = slow->next;
        slow->next = NULL;
        ListNode* reverseTmp2 = reverse(tmp2);
        
        ListNode* newHead = new ListNode(0);
        ListNode* returnHead = newHead;
        
        while(tmp1 && reverseTmp2) {
            ListNode* tmp1_next = tmp1->next;
            ListNode* reverseTmp2_next = reverseTmp2->next;
            
            newHead->next = tmp1;
            newHead = tmp1;
            tmp1 = tmp1_next;
            
            newHead->next = reverseTmp2;
            newHead = reverseTmp2;
            reverseTmp2 = reverseTmp2_next;
        }
        newHead->next = tmp1;     // watch out the last NULL pointer.
        head = returnHead->next;
    }


你可能感兴趣的:(LeetCode 143. Reorder List)