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

本文介绍了一种使用栈和递归方法实现链表逆序打印的技术。通过两种不同的实现方式,详细展示了如何从链表的尾部开始打印到头部。

题目:

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

思路:

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

代码:

  递归版:

    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;
    }

  

转载于:https://www.cnblogs.com/llauser/p/7473159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值