LeetCode143—Reorder List

原题

原题链接

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


分析

比较简单的思路就是,按照原链表反着重新创建一个链表,然后69式,删去新链表里面多于的部分。
不过题目又说不让用多于的空间,只能“in place”,原地进行调整。

那就把链表拆开,分为两个链表,前半部分和后半部分。
1.前半部分不用修改。
2.后半部分做逆置操作。
3.69式插入

代码

class Solution
{
    private:
    void reverse(ListNode * &post)//逆置链表
    {

        if(post&&post->next)
        {
            ListNode *p1 = post;
            ListNode *p2 = post->next;
            ListNode *p3 = NULL;
            while(p2!=NULL)
            {
                p3=p2->next;
                p2->next=p1;
                p1=p2;
                p2=p3;
            }
            post->next=NULL;
            post=p1;
        }
        else
        {
            return ;
        }

    }
    public:
    void reorderList(ListNode * head)
    {
        if(!head)
            return ;
        int count=0;
        ListNode *p=head;
        while(p!=NULL)
        {
            p=p->next;
            count++;
        }
        count = (count+1)/2;//find pre
        ListNode *pre=head;
        ListNode *post=head;
        int t=count;
        while(--t)
        {
            post=post->next;
        }

        ListNode *r = post;
        post=post->next;
        r->next=NULL;
        //cout << post->val<<endl;
        //      cout << count << endl;

        reverse(post);

        ListNode *pPre=pre;
        ListNode *pPost=post;
        ListNode *pNext=NULL;

        while(pPost)
        {
            pNext=pPost->next;
            pPost->next=pPre->next;
            pPre->next=pPost;
            pPre=pPost->next;
            pPost=pNext;
        }
        head=pre; 

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值