描述
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
解決之道
從頭到尾遍歷一遍,將元素放入容器中,然後,再將容器逆序
code
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> rt;
stack<struct ListNode*> ns;
struct ListNode* p = head;
while(p != NULL){
ns.push(p);
p = p->next;
}
while(!ns.empty()){
p = ns.top();
rt.push_back(p->val);
ns.pop();
}
return rt;
}
};