解题思路
栈法: 双百
利用栈结构的特性,先进后出
递归法:
同样利用栈的特性,因为递归在本质上就是一个栈结构
代码
//栈法
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<ListNode*> tempS;//中间结果保存到栈中
vector<int> ans;
while (head!=nullptr)
{
tempS.push(head);
head = head->next;
}
while (!tempS.empty())
{
ans.push_back(tempS.top()->val);
tempS.pop();
}
return ans;
}
};
//递归法
class Solution {
public:
vector<int> ans;
vector<int> reversePrint(ListNode* head) {
print(head);
return ans;
}
void print(ListNode* head) {
if (head != nullptr) {
if (head->next != nullptr) {
print(head->next);
}
ans.push_back(head->val);
}
}
};