[LeetCode] Reorder List 鏈表重排序

 

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…html

You may not modify the values in the list's nodes, only nodes itself may be changed.node

Example 1:post

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:url

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

 

這道鏈表重排序問題能夠拆分爲如下三個小問題:spa

1. 使用快慢指針來找到鏈表的中點,並將鏈表從中點處斷開,造成兩個獨立的鏈表。指針

2. 將第二個鏈翻轉。code

3. 將第二個鏈表的元素間隔地插入第一個鏈表中。htm

 

解法一:blog

class Solution {
public:
    void reorderList(ListNode *head) {
        if (!head || !head->next || !head->next->next) return;
        ListNode *fast = head, *slow = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *mid = slow->next;
        slow->next = NULL;
        ListNode *last = mid, *pre = NULL;
        while (last) {
            ListNode *next = last->next;
            last->next = pre;
            pre = last;
            last = next;
        }
        while (head && pre) {
            ListNode *next = head->next;
            head->next = pre;
            pre = pre->next;
            head->next->next = next;
            head = next;
        }
    }
};

 

咱們嘗試着看可否寫法上簡潔一些,上面的第二步是將後半段鏈表翻轉,那麼咱們其實能夠藉助棧的後進先出的特性來作,若是咱們按順序將全部的結點壓入棧,那麼出棧的時候就能夠倒序了,實際上就至關於翻轉了鏈表。因爲只需將後半段鏈表翻轉,那麼咱們就要控制出棧結點的個數,還好棧能夠直接獲得結點的個數,咱們減1除以2,就是要出棧結點的個數了。而後咱們要作的就是將每次出棧的結點隔一個插入到正確的位置,從而知足題目中要求的順序,鏈表插入結點的操做就比較常見了,這裏就很少解釋了,最後記得斷開棧頂元素後面的結點,好比對於 1->2->3->4,棧頂只需出一個結點4,而後加入原鏈表以後爲 1->4->2->3->(4),由於在原鏈表中結點3以後是連着結點4的,雖然咱們將結點4取出插入到結點1和2之間,可是結點3後面的指針仍是連着結點4的,因此咱們要斷開這個鏈接,這樣纔不會出現環,因爲此時結點3在棧頂,因此咱們直接斷開棧頂結點便可,參見代碼以下:排序

 

解法二:

class Solution {
public:
    void reorderList(ListNode *head) {
        if (!head || !head->next || !head->next->next) return;
        stack<ListNode*> st;
        ListNode *cur = head;
        while (cur) {
            st.push(cur);
            cur = cur->next;
        }
        int cnt = ((int)st.size() - 1) / 2;
        cur = head;
        while (cnt-- > 0) {
            auto t = st.top(); st.pop();
            ListNode *next = cur->next;
            cur->next = t;
            t->next = next;
            cur = next;
        }
        st.top()->next = NULL;
    }
};

 

參考資料:

https://leetcode.com/problems/reorder-list/

https://leetcode.com/problems/reorder-list/discuss/45175/Java-solution-with-stack

https://leetcode.com/problems/reorder-list/discuss/44992/Java-solution-with-3-steps

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索