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

利用一个堆栈,现将数组中的数值依次放入堆栈中,之后从堆栈中依次取出就是从尾到头顺序了。

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        stack<int> stack;
        vector<int> temp;

        while (head) {
            stack.push(head->val);
            head = head->next;
        }
        
        while (!stack.empty()) {
            temp.push_back(stack.top());
            stack.pop();
        }

        return temp;
    }
};

猜你喜欢

转载自blog.csdn.net/jcl314159/article/details/119616594