4種方法詳解:劍指Offer 06. 從尾到頭打印鏈表

原題LeetCode鏈接:劍指Offer 06. 從尾到頭打印鏈表

題目:劍指Offer 06. 從尾到頭打印鏈表

輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。

示例1:
輸入:head = [1,3,2]
輸出:[2,3,1]
0 <= 鏈表長度 <= 10000

思路一:reverse()方法

​ 遍歷鏈表,將遍歷到的元素依次插入到vector中,然後調用reverse方法反轉即可。時間複雜度:O(n),空間複雜度:O(1)C++代碼如下:

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        if(head == NULL) return res;
        ListNode* p = head;
        while(p != NULL){
            res.push_back(p->val);
            p = p->next;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

思路二:反轉鏈表法

​ 首先將鏈表反轉,再遍歷鏈表依次將鏈表元素插入到vector中。時間複雜度O(n),空間複雜度O(1)。缺點是要修改鏈表結構。C++代碼如下:

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        if(head == NULL) return res;
        ListNode* pre = NULL, * cur = head, *next = head;
        while(cur != NULL){
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        while(pre != NULL){
            res.push_back(pre->val);
            pre =pre->next;
        }
        return res;
    }
};

以上兩種方法是我自己想到的,接下來兩個方法是看別人的題解學習到的。

思路三:輔助棧法

​ 藉助棧“後進先出”的特性,可以實現反轉。依次遍歷鏈表同時將元素加入棧中直至遍歷完成。然後從棧中彈出元素插入到數組中直至棧空即可。時間複雜度:O(n),空間複雜度:O(n)C++代碼如下:

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> res;
        if(head == NULL) return res;
        stack<int> st;
        ListNode* p = head;
        while(p != NULL){
            st.push(p->val);
            p = p->next;
        }
        while(!st.empty()){
            res.push_back(st.top());
            st.pop();
        }
        return res;
    }
};

思路四:遞歸法

時間複雜度:O(n).空間複雜度:O(n)C++代碼如下:

class Solution {
public:
    vector<int> res;
    vector<int> reversePrint(ListNode* head) {
        if(head == NULL) return res;
        reversePrint(head->next);
        res.push_back(head->val);
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章