Leetcode Reorder List 143

本文介绍了一种链表重构算法,该算法将链表L0→L1→…→Ln-1→Ln重新排列为L0→Ln→L1→Ln-1→L2→Ln-2→…。具体步骤包括:使用双指针找到链表中点并将其分为两部分;翻转后半部分链表;最后将前后两部分链表交替合并。

摘要生成于 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}.

题目链接

在链表问题中,考虑到“原地“ 意味着在已有链表通过拆分-合并来解决问题
这题目分为三步:
1 . 通过双指针扫描,找到中间节点,分为两部分;
2. 把后半部分进行翻转
3. 把翻转的部分和前半部分链表合并

/**
 * 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) return ;
        //分为两部分
        ListNode *fast=head;
        ListNode *slow=head;

        while(1){
                fast=fast->next;
                if(fast==NULL)
                    break;
                fast=fast->next;
                if(fast==NULL)
                    break;
                slow=slow->next;
        }

        if(slow==NULL) return;
         // 后半部分翻转
        ListNode *cur=slow;
        ListNode *pre=slow->next;
        cur->next=NULL;
        while(pre!=NULL){
                ListNode *temp=pre->next;
                pre->next=cur;
                cur=pre;
                pre=temp;
        }

         //合并两个链表
        ListNode *first=head;
        ListNode *second=cur;

        while(first!=NULL && second!=NULL && first!=second){
                ListNode *temp=second->next;
                second->next=first->next;
                first->next=second;
                first=second->next;
                second=temp;
        }

        return ;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值