06.从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
遍历然后反转
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
while(head)
{
res.push_back(head->val);
head = head->next;
}
//使用algorithm算法中的reverse反转res
reverse(res.begin(),res.end());
return res;
}
};
栈
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> s;
vector<int> res;
//入栈
while(head){
s.push(head->val);
head = head->next;
}
//出栈
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
}
};
递归
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
if(head == nullptr)
return res;
reversePrint(head->next);
res.push_back(head->val);
return res;
}
};