Leetcode 143. Reorder List

来源:互联网 发布:php有java难吗 编辑:程序博客网 时间:2024/05/20 19:19

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

s思路:
1. 这道题让把list后半部分reverse后插入前半部分。
2. 做法也是先用快慢指针找到中点,然后把后半部分reverse,最后把reverse的后半部分一个一个的插入到前半部分。问题分成三步,每一步都很独立,不需要交叉,和前面遇到的几个步骤交叉进行的问题比,这个就是简单的问题!

class Solution {public:    void reorderList(ListNode* head) {        //step 1:找中点!        if(!head) return;        ListNode* fast=head->next,*slow=head;        while(fast&&fast->next){//bug:用fast->next比用fast好            fast=fast->next?fast->next->next:NULL;            slow=slow->next;            }        //step 2: reverse the right half        ListNode* pnow=slow->next;        while(pnow&&pnow->next){//千年bug:在不知道pnow是否有的情况下,不要直接写pnow->next,需要加保护            //ListNode* pnext=pnow->next;            ListNode* pre=slow->next;            slow->next=pnow->next;            pnow->next=pnow->next->next;            slow->next->next=pre;        }        //step 3:merge         ListNode* l=head,*r=slow->next;        slow->next=NULL;//关键位置:把左右两部分断开!        while(l&&r){            ListNode* p=l->next,*q=r->next;            l->next=r;            r->next=p;            l=p;            r=q;        }    }};
0 0