码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-143-Reorder List

时间:2019-02-06 18:26:00      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:sel   des   边界值   not   list   linked   nod   amp   order   

算法描述:

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;
    }

 

LeetCode-143-Reorder List

标签:sel   des   边界值   not   list   linked   nod   amp   order   

原文地址:https://www.cnblogs.com/nobodywang/p/10353863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!