leetcode143. Reorder List

medium程度題

題目:

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

我想的是把n個節點存入容器,然後遍歷容器改造節點,時間複雜度O(N),空間複雜度O(N)

AC解:

class Solution {
public:
    void reorderList(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr)
            return ;
        vector<ListNode*> vec;
        //遍歷一遍鏈表,所有節點存入vec
        ListNode *cur = head;
        while (cur)
        {
            vec.push_back(cur);
            cur = cur->next;
        }
        //改造節點
        auto first = vec.begin();
        auto second = vec.end() - 1;
        while (first < second)
        {
            (*first)->next = *second;
            first++;
            (*second)->next = *first;
            second--;
        }
        
        (*first)->next = nullptr;
    }
};


另有一種空間複雜度O(1)的解法,把鏈表拆分成兩個,將後面的鏈表翻轉,然後合併兩個鏈表

AC解:

class Solution {
public:
    void reorderList(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr)
            return ;
        ListNode *fast = head,*slow = head,*prev = nullptr;
        //拆分鏈表
        while (fast && fast->next)
        {
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        
        prev->next = nullptr;
        slow = reverse(slow);
        //合併兩個鏈表
        ListNode *cur = head;
        while (cur->next)
        {
            ListNode *temp = cur->next;
            cur->next = slow;
            slow = slow->next;
            cur->next->next = temp;
            cur = temp;
        }
        
        cur->next = slow;
    }
    
    ListNode* reverse(ListNode *head)
    {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode *prev = head;
        for (ListNode *cur = head->next,*next = cur->next; cur;)
        {
            head->next = next;
            cur->next = prev;
            prev = cur;
            cur = next;
            
            next = next ? next->next : nullptr;
        }
        
        return prev;
    }
};

兩種解法時間性能上沒有差別


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章