1. 程式人生 > >LeetCode-143-Reorder List

LeetCode-143-Reorder List

|| pre != 組織 中間 color link amp listnode

算法描述:

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list‘s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

解題思路:分三步,1找到中間節點,2翻轉後半部分,3重新連接組織兩部分。註意邊界值。

    void reorderList(ListNode* head) {
        if(head==nullptr || head->next ==nullptr) return;
        
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast->next!=nullptr && fast->next->next!=nullptr){
            fast 
= fast->next->next; slow = slow->next; } ListNode* slowHead = reverseList(slow->next); slow->next=nullptr; fast=head; slow=slowHead; while(fast!=nullptr && slow!=nullptr){ ListNode* temp = fast->next; fast
->next=slow; slow=slow->next; fast->next->next = temp; fast=temp; } } ListNode* reverseList(ListNode* head){ if(head==nullptr) return nullptr; ListNode* dup = new ListNode(-1); while(head!=nullptr){ ListNode* temp = dup->next; dup->next=head; head=head->next; dup->next->next=temp; } return dup->next; }

LeetCode-143-Reorder List