题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
解题思路
利用栈后进先出的原理,将链表按顺序装入到到栈中,又由于最后要求返回vector类型的数据,再讲栈中数据按出栈,装入到vector类型的容器中,然后返回该vector类型的容器。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
# include<iterator>
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
// 定义一个栈,由于栈是后进先出,这样全部存进去后再输出就是倒叙了
stack<int> s;
// 循环将链表的数据存入栈中
while (head)
{
s.push(head->val);
head = head->next;
}
// 由于最后要求返回一个vector类型的数值,用V将stack类型弹出的数据按弹出循序装入
vector<int> v;
while (!s.empty())
{
v.push_back(s.top());
s.pop();
}
return v;
}
};