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

来源:互联网 发布:js 跳转url 隐藏参数 编辑:程序博客网 时间:2024/06/05 04:52

输入一个链表,从尾到头打印链表每个节点的值。

/***  struct ListNode {*        int val;*        struct ListNode *next;*        ListNode(int x) :*              val(x), next(NULL) {*        }*  };*/class Solution {public:    vector<int> printListFromTailToHead(ListNode* head)     {        vector<int> ans;        if(head == NULL)            return ans;        stack<int> s;        ListNode *p;        while(head)        {            s.push(head->val);            head = head->next;        }        while(!s.empty())        {            int t = s.top();            ans.push_back(t);            s.pop();        }        return ans;    }};
原创粉丝点击