leetcode 143. 重排链表(反转链表、重构链表、递归、容器)

题目描述:
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路:
1、先找到中间节点,然后翻转后半段,最后再插入到前半段
2、递归
3、使用容器存储

代码如下:
1、

class Solution {
public:
    ListNode* reverse(ListNode *head){
        ListNode *p1=NULL;
        ListNode *p2=head;
        ListNode *p3=head;
        while(p2){
            p3=p2->next;
            p2->next=p1;
            p1=p2;
            p2=p3;
        }
        return p1;
    }
    void reorderList(ListNode* head) {
        if(head==NULL||head->next==NULL) return;
        ListNode* slow=head,*fast=head;
        while(fast->next&&fast->next->next){//快慢指针找到中间结点
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode* needReverser=slow->next;//分成两段
        slow->next=NULL;
        needReverser=reverse(needReverser);//反转链表
        ListNode *cur=head;
        while(cur&&needReverser){//插入前端缝隙
            ListNode *curSec=needReverser;
            needReverser=needReverser->next;
            ListNode *nextcur=cur->next;
            curSec->next=cur->next;
            cur->next=curSec;
            cur=nextcur;
        }
    }
};

2、

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head||!head->next) return;
        ListNode *p=head;
        while(p->next->next){
            p=p->next;
        }
        ListNode *inserP=p->next;
        p->next=NULL;
        inserP->next=head->next;
        head->next=inserP;
        reorderList(inserP->next);
    }
};

3、

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head||!head->next) return;
        vector<ListNode*>vec;
        ListNode* p=head;
        while(p){
            vec.push_back(p);
            p=p->next;
        }
        int left=0;
        int right=vec.size()-1;
        while(left<right){
            vec[left]->next=vec[right];
            vec[right]->next=vec[left+1];
            right--;
            left++;
        }
        vec[left]->next=NULL;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值