剑指 Offer 06. 从尾到头打印链表
题目要求:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
方法一:非递归 由于我们需要逆序输出链表,因此我们可以先用一个数组正序保存链表,再将数组逆置即可。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
while(head)
{
v.push_back(head->val);
head = head->next;
}
reverse(v.begin(),v.end());
return v;
}
};
方法二:使用栈结构 由于我们需要逆序输出 因此我们可以使用栈结构。首先遍历保存入栈,再使用数组按顺序出栈即可
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> s;
while(head)
{
s.push(head->val);
head = head->next;
}
vector<int> v;
while(!s.empty())
{
v.push_back(s.top());
s.pop();
}
return v;
}
};
方法三:使用递归
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
if(!head) return res;
reversePrint(head->next);
res.push_back(head->val);
return res;
}
};