分析:
emmm,想一想,正常的遍历链表的顺序是从前往后的,但是题目要求我们逆序打印,是不是很想栈的先进后出?既然是栈,除了直接用栈,我们是不是还能直接递归?
递归代码:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if(head==NULL) return {};
vector<int> ans=reversePrint(head->next);
ans.push_back(head->val);
return ans;
}
};
栈的代码:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> ans;
stack<int> s;
while(head)
{
s.push(head->val);
head=head->next;
}
while(!s.empty())
{
ans.push_back(s.top());
s.pop();
}
return ans;
}
};