从尾到头打印链表
- 递归
- 栈
递归写法
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head)
{
if (head == nullptr) return res;
print(head);
return res;
}
void print(ListNode* head)
{
if (head != nullptr)
{
if (head->next != nullptr)
{
reversePrint(head->next);
}
}
res.push_back(head->val);
}
};
栈
class Solution {
public:
vector<int> reversePrint(ListNode* head)
{
std::stack<int> nodes;
vector<int> array;
ListNode* pNode = head;
while(pNode != nullptr)
{
nodes.push(pNode->val);
pNode = pNode->next;
}
while(!nodes.empty())
{
array.push_back(nodes.top());
nodes.pop();
}
return array;
}
};