Leetcode -- Reorder List

本文介绍了一种链表重排序算法,通过将链表后半部分反转并交错地插入到前半部分,实现原地重排序,不改变节点值。提供了详细的算法分析及C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
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}.

分析:
将链表后半部分反转,然后插入到前半部分中

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reverseList(ListNode* &head)
    {
        if(!head || !head->next) return;

        ListNode* now = head;
        ListNode* pre = NULL;
        ListNode* next;
        while(now)
        {
            next = now->next;
            now->next = pre;
            pre = now;
            now = next;
        }
        head->next = next;
        head =  pre;
    }

 void reorderList(ListNode* head) {
        if(!head || !head->next || !head->next->next) return;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next != NULL && fast->next->next != NULL)
        {
            slow = slow ->next;
            fast = fast->next -> next;
        }
        fast = slow->next;
        slow->next = NULL;
        reverseList(fast);
        slow = head;

        ListNode* l1;
        ListNode* l2;
        while(slow && fast)
        {
            l1 = slow -> next;
            l2 = fast ->next;
            slow->next = fast;
            fast->next = l1;
            slow = l1;
            fast = l2;
        }
        return;
    }
};

注:调了十几年才搞定。只要问题是,函数调用,如何修改传进去的变量的指向.此外,反转总是会存在一些小细节容易出错,还是得多写写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值