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

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→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}.

    /**
     * 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||head->next==NULL||head->next->next==NULL)return;
        ListNode * slow=head;
        ListNode * fast=head;
        ListNode * pres=NULL;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            pres=slow;
            slow=slow->next;
        }
        pres->next=NULL;
        ListNode *tmp=new ListNode(0);
        tmp->next=slow;
        ListNode *last=slow;
        slow=slow->next;
        ListNode *p=NULL;
        while(slow&&slow->next)
        {
            p=tmp->next;
            tmp->next=slow;
            ListNode *later=slow->next;
            slow->next=p;
            slow=later;
        }
        if(slow)
        {
            p=tmp->next;
            tmp->next=slow;
            slow->next=p;
        }
        last->next=NULL;
        slow=tmp->next;
        fast=head;
        ListNode *f=NULL;
        while(fast&&slow)
        {
            p=slow->next;
            f=fast->next;
            fast->next=slow;
            if(f==NULL)
            {
                slow->next=p;
                break;
            }
            slow->next=f;
            fast=f;
            slow=p;
        }
    }
    /**
        void reorderList(ListNode *head) {
            if(head==NULL)return;
            vector<ListNode *> tmp;
            ListNode *p=head;
            while(p)
            {
                tmp.push_back(p);
                p=p->next;
            }
            int left=0,right=tmp.size()-1;
            while(left<right)
            {
                tmp[left]->next=tmp[right];
                left++;
                tmp[right]->next=tmp[left];
                right--;
                tmp[left]->next=tmp[right];
            }
            tmp[left]->next=NULL;
        }
    */
    };
  • 相关阅读:
    hdu5412CRB and Queries
    LCA rmq st model
    HDU 5348 MZL's endless loop
    2015多校联合训练赛 Training Contest 4 1008
    Bestcoder Tom and matrix
    TOJ 4105
    Codeforces D. Iahub and Xors
    Set 技巧之一
    1036: [ZJOI2008]树的统计Count
    一点点VIM
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281223.html
Copyright © 2011-2022 走看看