143. Reorder List**

143. Reorder List**

https://leetcode.com/problems/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 may not modify the values in the list’s nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

C++ 实现 1

基本思路:

  1. 首先找到链表的中点, 将链表分为前半部分 pre 和后半部分 post
  2. 翻转后半部分 post
  3. 合并前半部分 pre 以及翻转后的 post

查找链表的中点可以使用快慢指针.

class Solution {
private:
    ListNode* reverse(ListNode *head) {
        ListNode *prev = nullptr;
        while (head) {
            auto tmp = head->next;
            head->next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next) return;
        // 第一步
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        auto rlist = slow->next;
        slow->next = nullptr;
        // 第二步
        rlist = reverse(rlist);
        // 第三步
        ListNode *dummy = new ListNode(0);
        auto p = dummy;
        bool choose = true;
        while (head && rlist) {
            if (choose) {
                p->next = head;
                head = head->next;
            } else {
                p->next = rlist;
                rlist = rlist->next;
            }
            p = p->next;
            choose = !choose;
        }
        p->next = head ? head : rlist;
        head = dummy->next;
    }
};

C++ 实现 2

下面代码中的 merge 操作值得细细品味. 可以发现 head 指向整条链表, 而 ptr 指向翻转后的后半部分链表, 代码这样写没有问题. 思路有点像: 160. Intersection of Two Linked Lists*.

class Solution {
private:
    ListNode* reverse(ListNode *head) {
        ListNode *prev = nullptr;
        while (head) {
            auto tmp = head->next;
            head->next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }

    void merge(ListNode *l1, ListNode *l2) {
        for (auto p1 = l1, p2 = l2; p1; ) {
            auto t = p1->next;
            p1->next = p2;
            p1 = p1->next;
            p2 = t;
        }
    }
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next)
            return;

        ListNode *slow = head, *fast = head->next;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        auto ptr = reverse(slow->next);
        merge(head, ptr);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值