【题目】
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
来源:leetcode
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
【示例】
输入:head = [1,3,2]
输出:[2,3,1]
【限制】
0 <= 链表长度 <= 10000
【思想】
借助栈完成,先从头到尾访问链表,在访问的过程中让节点数字进栈,当链表访问完之后,所有的数字都在栈内,然后依次出栈压入vector数组中。
【代码】
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
stack<int> s;
while(head){
s.push(head->val);
head=head->next;
}
while(!s.empty()){
v.push_back(s.top());
s.pop();
}
return v;
}
};