从尾到头打印链表——剑指Offer

https://www.nowcoder.net/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

题目描述

输入一个链表,从尾到头打印链表每个节点的值。
 
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> stk;
        
        ListNode *cur = head;
        while (cur != NULL) {
            stk.push(cur->val);
            cur = cur->next;
        }
        
        vector<int> ret;
        while (!stk.empty()){
            ret.push_back(stk.top());
            stk.pop();
        }
        return ret;
    }
};

 

结果:

通过
您的代码已保存
答案正确:恭喜!您提交的程序通过了所有的测试用例

 

 

posted @ 2018-02-07 00:58  blcblc  阅读(104)  评论(0编辑  收藏  举报