1、栈
考虑到我们需要逆序输出链表中的值,我们可以使用栈来记录链表中的值并最后逆序输出。
class Solution {
public:
vector<int> reversePrint(ListNode *head) {
stack<int> st;
vector<int> res;
while (head != nullptr) {
st.push(head->val);
head = head->next;
}
while (!st.empty()) {
res.push_back(st.top());
st.pop();
}
return res;
}
};
2、递归
考虑到栈可以实现,递归在本质上就是一个隐式的栈,因此本问题也可以使用递归解决。
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode *head) {
if (head != nullptr) {
reversePrint(head->next);
res.push_back(head->val);
}
return res;
}
};