Reorder List

本文详细阐述了如何通过快慢指针找到链表中点、反转后半部分链表,并将其与前半部分交替链接,实现链表的重组。通过实例演示了从原始链表到重组链表的完整过程。

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.


先用快慢指针找到能把原list切分两半的中点,然后把后半段list 反转,最后把前半段list和反转后的后半段list交替链接起来就行了。




/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) {
        if (head == NULL || head->next == NULL) return;
        ListNode *mo = head, *hi = head->next;
        while (hi != NULL && hi->next != NULL) {
            hi = hi->next->next;
            mo = mo->next;
        }
        
        ListNode *m1 = mo->next;
        mo->next = NULL;
        hi = reverseList(m1);
        mo = head;
        while (mo != NULL && hi != NULL) {
            m1 = mo->next;
            mo->next = hi;
            ListNode *h1 = hi->next;
            hi->next = m1;
            mo = m1;
            hi = h1;
        }
    }
private:
    ListNode *reverseList(ListNode *head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode *pre = head;
        ListNode *cur = head->next;
        head->next = NULL;
        while (cur != NULL) {
            ListNode *next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        return pre;
    }
};







评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值