LeetCode 143 重排連結串列 HERODING的LeetCode之路

HERODING23發表於2020-10-20

給定一個單連結串列 L:L0→L1→…→Ln-1→Ln ,
將其重新排列後變為: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

示例 1:

給定連結串列 1->2->3->4, 重新排列為 1->4->2->3.
示例 2:

給定連結串列 1->2->3->4->5, 重新排列為 1->5->2->4->3.

解題思路:
一個耗時長耗存多的方法,但是特別容易理解,遞迴!1->2->3->4,首先1指向4,並且斷掉3指向4的指標,然後4再指回1的next,就是2,這個時候再在2->3的集合中遍歷,由於連結串列長度短於3的連結串列直接返回即可,所以return,程式碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        exchange(head);
    }
    void exchange(ListNode * node){
        // 計算長度,如果長度小於等於2,說明到最中間了,返回
        int len = 0;
        ListNode * temp = node;
        while(temp != nullptr){
            temp = temp -> next;
            len ++;
            if(len > 2){
                break;
            }
        }
        if(len <= 2){
            return;
        }
        // 雙指標一個用於遍歷,一個用於指向下一個節點
        ListNode * temp1 = node -> next;
        ListNode * temp2 = node;
        //一直遍歷到倒數第二個指標
        while(temp2 -> next -> next != nullptr){
            temp2 = temp2 -> next;
        }
        ListNode * temp3 = temp2;
        ListNode * temp4 = temp2 -> next;
        // 斷開與最後一個節點的連線
        temp3 -> next = nullptr;
        node -> next = temp4;
        temp4 -> next = temp1;
        // 進行下一次交換
        exchange(temp4 -> next);
    }
};

/*作者:heroding
連結:https://leetcode-cn.com/problems/reorder-list/solution/fei-chang-rong-yi-li-jie-de-si-lu-by-heroding/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。*/

相關文章