leetcode141_重排鏈表

一.迭代

1. 將鏈表轉換爲數組,然後用雙指針分別取出頭尾指針.

2. 相當於耍賴用數組轉化鏈表.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //鏈表節點存數組.
    vector<ListNode*> tmp;
    void reorderList(ListNode* head) {
        if(head==NULL || head->next==NULL) return;
        while(head!=NULL) {
            tmp.push_back(head);
            head = head->next;
        }
        //頭尾依次取出元素.
        int i=0, j=tmp.size()-1;
        while(i<j) {
            tmp[i]->next = tmp[j];
            i++;
            if(i==j) break;
            tmp[j]->next = tmp[i];
            j--;
        }
        //i和j無所謂,但是一定得指向NULL.
        tmp[i]->next = NULL;
        return;
    }
};

二. 遞歸

1. 這題最大的好處就是返回值爲void. 這樣我們不用返回頭結點.

class Solution {
public:
    ListNode* helper(ListNode* head, int len) {
        //len更容易遞歸到終止條件.
        if(len==1) return head;
        if(len==2) return head->next;
        //返回head->next,len-2,即除去頭尾節點的上一個
        //重排的尾部節點.
        ListNode* tail = helper(head->next, len-2);
        //畫圖容易理解.tmp爲重排之前的最後一個節點.
        ListNode* tmp = tail->next;
        //頭尾頭尾順序連接鏈表.
        //注意tail->next應該連接他之後的節點,
        //這樣才能不停遞歸.
        tail->next = tail->next->next;
        tmp->next = head->next;
        head->next = tmp;
        //返回重排後鏈表的尾部節點.
        return tail;
    }
    void reorderList(ListNode* head) {
        if(head==NULL || head->next==NULL) return;
        int len = 0;
        ListNode* cur = head;
        while(cur!=NULL) {
            len++;
            cur = cur->next;
        }
        //helper函數的作用是給定頭結點和對應的鏈表長度,
        //返回重排鏈表的最後一個節點.
        ListNode* tail = helper(head, len);
    }
};

 

發佈了95 篇原創文章 · 獲贊 26 · 訪問量 2125
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章