法一:栈
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> stk;
ListNode * p=head;
while(p){
stk.push(p->val);
p=p->next;
}
vector<int> ans;
while(!stk.empty()){
ans.push_back(stk.top());
stk.pop();
}
return ans;
}
};
法二:递归:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> ans;
ListNode* p=head;
res(p,ans);
return ans;
}
void res(ListNode* p,vector<int> &ans){
if(p)
{
if(p->next)
{
res(p->next,ans);
}
ans.push_back(p->val);
}
}
};