剑指 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;
}
};

浙公网安备 33010602011771号