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

重排链表,设链表长为n+1,要求第n-m个结点(n,m = 0,1,2,……n)插入到第m个结点后。

其实就是沿着链表中点对称插入重排,而链表的特殊之处就在于不能走回头路,但我们可以把链表后半部分进行逆序,然后把前后两部分的链表合并就ok了。过程:

1-2-3-4-5-6-7-8
↓
1-2-3-4
5-6-7-8
↓
1-2-3-4
8-7-6-5
↓
1-8-2-7-3-6-4-5
class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next) return;

        //找中点
        ListNode *slow = head, *fast = head;
        while (fast->next && fast->next->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }

        //分割链表成两部分
        ListNode *midNode = slow->next;
        slow->next = NULL;

        //翻转链表后半部分
        ListNode *pre = midNode, *cur;
        while (pre && (cur = pre->next))
        {
            pre->next = cur->next;
            cur->next = midNode;
            midNode = cur;
        }

        //插入
        cur = head;
        ListNode *subCur;
        while ((subCur = midNode))
        {
            midNode = subCur->next;
            subCur->next = cur->next;
            cur->next = subCur;

            cur = cur->next->next;
        }
        //return head;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值