leetcode笔记:Reorder List

本文介绍了一种链表处理算法,包括链表分割、逆序操作和合并步骤,详细阐述了每一部分的实现过程及代码示例。通过对比原始与优化后的代码,突出了算法效率的提升。

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

一.题目描述

这里写图片描述

二.题目分析

直接按照题目的要求求解,设ListNode *head为待处理的链表,算法包括以下步骤:
1. 将链表head分为前后两部分,前半部分链表head1 和后半部分链表head2;
2. 将后半段链表head12做逆序操作;
3. 合并head1, head2;

三.示例代码

struct ListNode
{
    int value;
    ListNode *next;
    ListNode(int x) : value(x), next(NULL){};
};

class Solution
{
public:
    ListNode * reorderList(ListNode *head) {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode *slow = head;
        ListNode *fast = head;
        ListNode *cut = head;
        while (fast && fast->next)
        {
            cut = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        cut->next = NULL;

        slow = reverseList(slow);
        ListNode *result = mergeList(head, slow);
        return result;
    }

    ListNode* reverseList(ListNode *head) // 翻转链表
    {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode *prev = head;
        ListNode *curr = head->next;
        ListNode *temp = curr;
        prev->next = NULL;

        while (curr)
        {
            temp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = temp;    
        }
        return prev;
    }


    ListNode* mergeList(ListNode *head1, ListNode *head2)
    {
        ListNode* temp1 = head1;
        ListNode* temp2 = head2;
        ListNode* pMerge = head1;
        bool flag = true;

        while (temp1 != NULL && temp2 != NULL)
        {
            if (flag  && temp2 != NULL)
            {
                temp1 = head1->next;
                head1->next = temp2;
                head1 = head1->next;
                flag = false;
            }
            if (!flag  && temp1 != NULL)
            {
                temp2 = head1->next;
                head1->next = temp1;
                head1 = head1->next;
                flag = true;
            }
        }
        return pMerge;
    }
};

测试结果:

这里写图片描述

四.总结

这道题需要对链表进行翻转操作&对两个链表进行合并操作,实现本身不难,但代码只是随便一写,比较繁琐,需要后期再优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值