剑指 Offer 06. 从尾到头打印链表

题目

剑指 Offer 06. 从尾到头打印链表

代码

递归

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

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> s;
        vector<int> res;
        while(head) {
            s.push(head->val);
            head = head->next;
        }
        while(!s.empty()) {
            res.push_back(s.top());
            s.pop();
        }
        return res;
    }
};
posted @ 2022-04-17 16:36  当惜  阅读(15)  评论(0)    收藏  举报