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


题目

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

代码

递归

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

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