Reorder List

题目链接:

https://leetcode.com/problems/reorder-list/description/

描述

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

样例输入

样例输出

算法思想:

先把表等分成a与b两个链表,然后把b逆序,最后把a和b链表交叉合并起来即可

源代码

class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head)
            return ;
        ListNode *a, *b;
        //分离链表分成一半一半
        a = head;
        b = head->next;
        while (b)
        {
            b = b->next;
            if (b)
            {
                a = a->next;
                b = b->next;
            }
        }
        b = a->next;
        a->next = NULL;
        a = head;
        //让b链表逆序
        if (b)
        {
            ListNode *current = b->next;
            ListNode *tem = current;
            b->next = NULL;
            while (current)
            {
                current = current->next;
                tem->next = b;
                b = tem;
                tem = current;
            }
        }
        //合并2个链表
        ListNode *a1, *a2, *b1;
        a1 = a; a2 = a1->next;
        b1 = b;
        while (b)
        {
            b = b->next;
            a1->next = b1;
            b1->next = a2;
            b1 = b;
            a1 = a2;
            if (a1)
                a2 = a1->next;

        }
    }
};

最优源代码

算法复杂度:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值