【劍指**】6.從尾到頭打印鏈表

6.從尾到頭打印鏈表

題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

題目很經典,因此本文用三種方法來處理。(嚴格來說算2種)

思路1

先順序輸出鏈表數據,然後翻轉輸出的結果。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        if (head == NULL) return {};
        vector<int> ret;
        ListNode* pRead = head;
        while(pRead != NULL) {
            ret.push_back(pRead->val);
            pRead = pRead->next;
        }
        std::reverse(ret.begin(), ret.end());
        return ret;
    }
};

從頭到位遍歷一遍數據,因此時間複雜度:O(n)

空間複雜度:O(n)

思路2 棧 非遞歸

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        if (head == NULL) return {};
        std::stack<ListNode*> sk;
        ListNode* pRead = head;
        while (pRead != NULL) {
            sk.push(pRead);
            pRead = pRead->next;
        }
        vector<int> ret;
        while (!sk.empty()) {
            ret.push_back(sk.top()->val);
            sk.pop();
        }
        return ret;
    }
};

思路3 棧 遞歸

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