剑指offer-从尾到头打印链表

本文介绍三种方法实现链表值从尾到头的逆序输出:利用ArrayList库函数直接逆序添加;使用递归调用,先处理下一节点再添加当前节点值;运用栈的先进后出特性,先压栈所有节点值再弹出至ArrayList中。

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

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
 
方法一:利用ArrayList库函数
1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 my
2         ArrayList<Integer> re = new ArrayList<Integer>();
3         while(null!=listNode){
4             re.add(0,listNode.val);
5             listNode = listNode.next;
6         }
7         return re;
8     }

方法二:使用递归

1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 递归 mytip
2         if(null==listNode){
3             return new ArrayList<Integer>();
4         }
5         ArrayList<Integer> re = printListFromTailToHead(listNode.next);
6         re.add(listNode.val);
7         return re;
8     }

方法三:使用栈

 1 public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {//链表 栈 mytip
 2         Stack<Integer> stack = new Stack<Integer>();
 3         while(null!=listNode){
 4             stack.push(listNode.val);
 5             listNode = listNode.next;
 6         }
 7         ArrayList<Integer> re = new ArrayList<Integer>(stack.size());
 8         while(!stack.isEmpty()){
 9             re.add(stack.pop());
10         }
11         return re;
12     }

 

转载于:https://www.cnblogs.com/zhacai/p/10675997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值