首页 > 其他 > 详细

3,从尾到头打印链表 《剑指offer》

时间:2017-09-04 14:27:49      阅读:218      评论:0      收藏:0      [点我收藏+]

题目:

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

思路:

很容易想到用栈实现,后进先出;遍历一遍节点压栈,弹出栈的数值;也可以用递归实现;

代码:

  递归版:

    vector<int> res;
    vector<int> printListFromTailToHead(ListNode* head) {
        if(head==NULL) return res;
        if(head->next!=NULL) printListFromTailToHead(head->next);
        res.push_back(head->val);
        return res;
    }

  用栈实现:

//c++
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
        if(head==NULL) return res;
        ListNode* p=head;
        stack<int> q;
        while(p!=NULL){
            q.push(p->val);
            p=p->next;
        }
        while(!q.empty()){
            res.push_back(q.top());
            q.pop();
        }
        return res;
    }

  

3,从尾到头打印链表 《剑指offer》

原文:http://www.cnblogs.com/llauser/p/7473159.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!