【从尾到头打印链表】递归与栈的直接联系

一、题目

在这里插入图片描述

二、解法

  • 对于该题,我首先想到的是利用栈的数据结构。由于遍历链表只能顺序进行,那可以不断将节点的值压入栈中,遍历完成后,将栈顶元素添加到数组中,并进行出栈操作(即删除栈顶元素)。
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
#include <vector>
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        stack<int> stk;
        vector<int> res;
        while (head!=nullptr){
            stk.push(head->val);
            head = head->next;
        }
        while (!stk.empty()){
            res.emplace_back(stk.top());
            stk.pop();
        }
        return res;
    }
};

  • 递归算法的底层实现其实也利用了栈这种数据结构,也就是说,递归在不断递下去的过程中,需要保存函数的参数,变量等,即需要入栈,而到达边界条件以后,需要不断返回到上一级问题,即需要出栈。那么该问题也可以采用递归算法:
    1)确定非边界条件:可以这么考虑,从头节点开始,不断遍历到尾结点,将head作为递归函数的参数,不断递下去,不做任何操作;
    2)边界条件:遍历到尾节点时,即head为空时,直接退出递归函数,
    到达边界条件以后,就可以将尾结点的值添加到数组中。

python代码:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param listNode ListNode类 
# @return int整型一维数组
#
import sys
"""设置递归深度,python中递归深度是有限制的。一般默认为999,当超过999时,会出现错误:
RuntimeError: maximum recursion depth exceeded while calling a Python object"""
sys.setrecursionlimit(100000)
class Solution:
    def reverse_list(self, head: ListNode, res: List[int]):
        if (head != None):
            res = self.reverse_list(head.next, res)
            res.append(head.val)
        return res


    def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
        # write code here
        res = []
        res = self.reverse_list(listNode, res)
        return res

C++代码:

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    //递归函数
    void recursion(ListNode* head, vector<int>& res){ 
        if(head != NULL){
            //先往链表深处遍历
            recursion(head->next, res); 
            //再填充到数组就是逆序
            res.push_back(head->val); 
        }
    }
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        //递归函数打印
        recursion(head, res); 
        return res;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值