5.从尾到头打印链表

从尾到头打印链表

1.题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

2.思路

利用栈实现,没遍历一个节点就插入栈。

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;
        if(head == NULL){
            return res;
        }
        stack<int> s;
        while(head != NULL){
            s.push(head->val);
            head = head->next;
        }
        while(!s.empty()){
            int val = s.top();
            s.pop();
            res.push_back(val);
        }
        return res;
    }
};

4.复杂度分析

时间复杂度:O(n)
空间复杂度:O(n)

发布了71 篇原创文章 · 获赞 0 · 访问量 805

猜你喜欢

转载自blog.csdn.net/jiangdongxiaobawang/article/details/103914733