剑指offer 06. 从尾到头打印链表

剑指 Offer 06. 从尾到头打印链表 - 力扣(LeetCode) (leetcode-cn.com)

目录

方案1

运行结果

代码

方案2

运行结果

代码


方案1

遍历一遍链表,把所有元素按正序放进一个数组里面,并得出栈的元素个数,此时再将数组逆序输出。

运行结果

代码

class Solution {
#define scale 0x2710
public:
    vector<int> reversePrint(ListNode* head) {
        int* arr = new int[scale];
        int count = 0;
        for (ListNode* iter = head; iter != NULL; iter = iter->next)
            arr[count++] = iter->val;
        vector<int> ans(count);
        for (auto& x : ans)
            x = arr[--count];
        return ans;
    }
};

方案2

 遍历是从头到尾,输出是从尾到头,典型的后进先出,可以考虑用栈:遍历的时候逐个压栈,最后从栈中逐个取出。(不难实现,这里就不放代码了)

既然想到了用栈来实现,递归在本质上就是一个栈结构,于是很自然地又想到了用递归来实现。我们每访问一个节点,首先递归输出它后面的节点,然后再输出该节点自身,这样整个链表的输出结果就反过来了。

运行结果

代码

class Solution {
    vector<int> ans;
public:
    vector<int> reversePrint(ListNode* head) {
        _reverse(head);
        return ans;
    }

    void _reverse(ListNode* node) {
        if (node) {
            _reverse(node->next);
            ans.push_back(node->val);
        }
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值