1、思路一:利用递归实现
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>res;
if(head==NULL){
return res;
}
ListNode* cur=head;
if(cur!=NULL){
if(cur->next!=NULL){
res=printListFromTailToHead(cur->next);
}
res.push_back(cur->val);
}
return res;
}
};
2、思路二:借助栈实现
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>res;
std::stack<int>s;
ListNode* cur=head;
if(cur==NULL){
return res;
}
while(cur!=NULL){
s.push(cur->val);
cur=cur->next;
}
while(!s.empty()){
int val=s.top();
res.push_back(val);
s.pop();
}
return res;
}
};