(链表)从尾到头打印链表

2019-03-16  本文已影响0人  new_liziang

题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路
将链表的val存到stack里,在输出到vector里面。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        vec.clear();
        if(head == NULL)
            return vec;
        std::stack<int> s;
        while(head != NULL)
        {
            s.push(head->val);
            head = head->next;
        }
        
        while(!s.empty())//注意栈的循环条件
        {
            vec.push_back(s.top());
            s.pop();
        }
        return vec;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读