剑指offer-----3、从尾到头打印链表

1、题目描述

        输入一个链表,从尾到头输出其节点值。

2、分析

        这道题很简单,利用一个栈,遍历一遍链表,将节点值push进栈,然后再将栈内元素输出。

3、代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        stack<int> store;
        ListNode* temp=head;
        while(temp!=NULL){
            store.push(temp->val);
            temp=temp->next;
        }
        while(!store.empty()){
            res.push_back(store.top());
            store.pop();
        }
        return res;
    }
};

4、相关知识点

        对栈的概念、链表的概念都要熟悉。

posted @ 2019-05-20 17:50  吾之求索  阅读(76)  评论(0)    收藏  举报