剑指 Offer 06. 从尾到头打印链表
递归做法
class Solution {
public:
vector<int> res;
vector<int> printListReversingly(ListNode* head) {
if(!head) return {};
dfs(head);
return res;
}
void dfs(ListNode* head) {
if(!head) return; //边界返回
dfs(head -> next);//先递归
res.push_back(head -> val);//再将值压入数组
}
};
使用栈辅助翻转
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
stack<int> st;
auto p = head;
while(p) {
st.push(p -> val);
p = p -> next;
}
while(!st.empty()) {
res.push_back(st.top());
st.pop();
}
return res;
}
};