題目描述
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
解題思路
首先將鏈表中的值從頭到尾壓入一個棧中,然後再依次將值從棧中讀取出來。
利用棧的先進後出原理即可。
代碼
/**
* 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;
}
};