lc 143.重排链表【****①找中间结点;②翻转中间结点之后的链表,形成两个链表;③合并两个链表】

官方题解https://leetcode-cn.com/problems/reorder-list/solution/zhong-pai-lian-biao-by-leetcode-solution/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head || !head->next) return;
        //找中间结点
        ListNode* mid=FindMid(head);
        //中间结点之后翻转,成为新的链表
        ListNode *l1=head, *l2=mid->next;
        mid->next=NULL;
        l2=reverse(l2);
        //两个链表合并
        merge(l1,l2);
    }

    ListNode* FindMid(ListNode* head){
        ListNode *fast=head, *slow=head;
        while(fast && fast->next){
            fast=fast->next->next;
            slow=slow->next;
        }
        return slow;
    }

    ListNode* reverse(ListNode* head){
        ListNode *pre=NULL, *p=head, *next=NULL;
        while(p){
            next=p->next;
            p->next=pre;
            pre=p;
            p=next;
        }
        return pre;
    }

    ListNode* merge(ListNode* h1, ListNode* h2){
        ListNode *h1_next=NULL, *h2_next=NULL;
        while(h1 && h2){
            h1_next=h1->next;
            h2_next=h2->next;

            h1->next=h2;
            h2->next=h1_next;

            h1=h1_next;
            h2=h2_next;
        }
        return h1;
    }
};

例子:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值