剑指offer66题 -- 输入一个链表,从尾到头打印链表每个节点的值

本文介绍了一种使用递归方法来实现从尾到头打印链表的方法。此方法不需要额外的数据结构来辅助,通过递归调用即可实现链表元素的逆序输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
  /*
    //变量定义区
    vector<int> result;
    std::stack<int> stk;
    ListNode* current = head;

    //入参有效性判断
    if(NULL == head)
       return result;

    //数据入栈
    while(current != NULL)
    {
        stk.push(current->val); //stack入栈函数push函数
        current = current->next;
    }

    //数据出栈
    while(!stk.empty())
    {
        int val = stk.top();
        result.push_back(val); //vector添加操作
        stk.pop();
     }
     return result;
    */

    //递归实现
    ListNode* current = head;
    vector<int> result;
    if(current != NULL)
    {
       if(current->next !=NULL)
      {
           result = printListFromTailToHead(current->next);
      }
     result.push_back(current->val); 

    }

    return result;
}
};

 

程序已通过牛客网测试用例。

转载于:https://www.cnblogs.com/shewell/p/6446047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值