zoukankan      html  css  js  c++  java
  • leetcode 143 Reorder List

    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;
            }
        }
    };
  • 相关阅读:
    CentOS安装KDE
    __builtin_expect — 分支预测优化
    Linux中CPU亲和性(affinity)
    字节序
    gethostbyname
    字符串搜索算法
    排序算法
    Linux下使用http协议下载文件
    POSIX Timer
    POSIX-Data Structure
  • 原文地址:https://www.cnblogs.com/LiuQiujie/p/12657980.html
Copyright © 2011-2022 走看看