【劍指Offer】面試題06.從尾到頭打印鏈表

題目

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

示例 1:

輸入:head = [1,3,2]
輸出:[2,3,1]

限制:
0 <= 鏈表長度 <= 10000

思路一:反轉數組

代碼

時間複雜度:O(n)
空間複雜度:O(1)

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

思路二:棧

代碼

時間複雜度:O(n)
空間複雜度:O(n)

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