LeetCode: Reorder List [143]

來源:互聯網
上載者:User

標籤:leetcode   演算法   面試   

【題目】

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


【題意】

    給定一個鏈表L: L0→L1→…→Ln-1→Ln,對他重新排序成L0→Ln→L1→Ln-1→L2→Ln-2→…


【思路】

        將鏈表對半截斷,將後半部分鏈表倒置,然後把前後兩個鏈表錯位合并
        本題涉及三個典型的鏈表操作:
        1. 找鏈表中點
        2. 鏈表倒置
        3. 鏈表歸併


【代碼】
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reserve(ListNode *head){        if(head==NULL || head->next==NULL)return head;        ListNode* prev=NULL;        ListNode* cur=head;        ListNode* next=NULL;        while(cur){            next=cur->next;            cur->next=prev;            prev=cur;            cur=next;        }        return prev;    }    ListNode* findMid(ListNode *head){        if(head==NULL || head->next==NULL)return head;        ListNode*prev=NULL;        ListNode*p1=head;        ListNode*p2=head;        while(p2){            prev=p1;            p1=p1->next;            p2=p2->next;            if(p2)p2=p2->next;        }        prev->next=NULL;        return p1;    }    ListNode* merge(ListNode*head1, ListNode*head2){        ListNode*p1=head1;        ListNode*p2=head2;        ListNode*head=NULL, *p=NULL;        while(p2){            if(head==NULL)head=p1;             else p->next=p1;            p=p1;            p1=p1->next;            p->next=p2;            p=p2;            p2=p2->next;        }        p->next=p1;        return head;    }    void reorderList(ListNode *head) {        if(head==NULL || head->next==NULL)return;        ListNode* head2 = findMid(head);        head2 = reserve(head2);        head=merge(head, head2);    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.