码迷,mamicode.com
首页 > 其他好文 > 详细

从尾到头打印链表

时间:2018-03-01 00:37:53      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:print   思想   null   递归   一个   col   掌握   vector   pre   

题目:

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

 

做法一:最初的思路:将链表元素压入栈,在弹出到队列

    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> vec;
        stack<int> sta;
        ListNode* p = head;
        while(p != NULL)
        {
            sta.push(p->val);
            p = p->next;
        }
        int num = sta.size();
        while(num--)
        {
            vec.push_back(sta.top());
            sta.pop();
        }
        return vec;
    }

做法二:递归(能不用就不用,主要掌握思想)

    vector<int> vec;
    void func(ListNode* p)
    {
        if(p == NULL)
            return;
        func(p->next);
        vec.push_back(p->val);
    }
    vector<int> printListFromTailToHead(ListNode* head) {
        func(head);
        return vec;
    } 

从尾到头打印链表

标签:print   思想   null   递归   一个   col   掌握   vector   pre   

原文地址:https://www.cnblogs.com/Lune-Qiu/p/8486245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!