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;
        }
    */
    };
  • 相关阅读:
    项目质量管理
    项目成本管理
    项目进度管理
    项目范围管理
    项目整体管理
    项目立项管理
    信息系统项目管理基础
    信息化和信息系统
    linux(3)
    Patorjk
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281223.html
Copyright © 2011-2022 走看看