描述
输入一个链表,从尾到头打印链表每个节点的值。
解决之道
从头到尾遍历一遍,将元素放入容器中,然后,再将容器逆序
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;
}
};