牛客网刷题--剑指offer(从尾到头打印链表)

来源:互联网 发布:条码打印软件免费版 编辑:程序博客网 时间:2024/06/07 00:20

题目描述:
输入一个链表,从尾到头打印链表每个节点的值。
单向链表只能从头到尾打印元素,而题目要求是从尾到头打印,顺序做了一个颠倒,这时就要用到了栈(后进先出)。
代码粘贴如下:

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

若有不对之处,敬请指正。。

0 0