(链表)从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个vector。

https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

来实现后进先出。先将链表从头到尾push到栈s中,再逐一从栈s中pop出来。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<ListNode*> s;
        ListNode* p = head;
        while(p){
            s.push(p);
            p = p->next;  //将链表从头到尾加入栈中
        }
        vector<int> res;
        while(!s.empty()){
            p = s.top();
            res.push_back(p->val);
            s.pop();
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/Bella2017/p/11819910.html