首页 > 其他 > 详细

leetcode 143 Reorder List

时间:2020-04-08 10:02:52      阅读:43      评论:0      收藏:0      [点我收藏+]

1. 

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head) return;
        vector<ListNode*> vec;
        ListNode* slow=head,*fast=head,*pre=nullptr;
        while(fast&&fast->next) {
            pre=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        if(fast) {
            pre=slow;
            slow=slow->next;
        }
        pre->next=nullptr;
        while(slow) {
            vec.push_back(slow);
            slow=slow->next;
        }
        slow=head;
        for(int i=vec.size()-1;i>=0&&slow;--i) {
            ListNode *node=vec[i],*tmp=slow->next;
            slow->next=node;node->next=tmp;
            slow=slow->next->next;
        }
    }
};

2. 

class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head) return;
        ListNode* slow=head,*fast=head,*pre=nullptr;
        while(fast&&fast->next) {
            pre=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        if(fast) {
            pre=slow;
            slow=slow->next;
        }
        pre->next=nullptr;
        pre=nullptr;
        while(slow) {
            ListNode* next=slow->next;
            slow->next=pre;
            pre=slow;
            slow=next;
        }
        slow=head;
        while(slow&&pre) {
            ListNode* nextl=slow->next,*nextr=pre->next;
            slow->next=pre;
            pre->next=nextl;
            slow=nextl;
            pre=nextr;
        }
    }
};

 

leetcode 143 Reorder List

原文:https://www.cnblogs.com/LiuQiujie/p/12657980.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!