题目描述
输入一个链表,从尾到头打印链表每个节点的值。
解题思路
首先将链表中的值从头到尾压入一个栈中,然后再依次将值从栈中读取出来。
利用栈的先进后出原理即可。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<int> mystack;
while (head) {
mystack.push(head->val);
head = head->next;
}
while (!mystack.empty()) {
res.push_back(mystack.top());
mystack.pop();
}
return res;
}
};