剑指Offer 从尾到头打印链表

时间限制:1秒 空间限制:32768K 热度指数:551083
本题知识点: 链表

 算法知识视频讲解

题目描述

输入一个链表,从尾到头打印链表每个节点的值。
给出代码:
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        
    }
};

 

用栈来反着输出

 

AC代码:

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        ListNode* p = head;
        stack<int> sta;
        int num = 0;
        while(p != NULL) {
            sta.push(p->val);
            p = p->next;
        }
        while(!sta.empty()) {
            num = sta.top();
            sta.pop();
            vec.push_back(num);
         }
        return vec;
    }
};

  

 

posted @ 2018-07-02 15:43  Hyouka  阅读(127)  评论(0编辑  收藏  举报