LeetCode-143-Reorder List

算法描述:

Given a singly linked list LL0→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;
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10353863.html