JZ-003-从尾到头打印链表
2024-09-08 06:22:25
从尾到头打印链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题目链接: 从尾到头打印链表
代码
import java.util.ArrayList;
/**
* 标题:
* 题目描述
*
* <p>
* 题目链接
*
*/
public class Jz03 {
/**
* 非递归
*
* @param listNode
* @return
*/
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<>();
for (; listNode != null; listNode = listNode.next) {
res.add(0, listNode.val);
}
return res;
}
/**
* 递归
*
* @param listNode
* @return
*/
public static ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (listNode != null) {
res.addAll(printListFromTailToHead1(listNode.next));
res.add(listNode.val);
}
return res;
}
public static void main(String[] args) {
ListNode node = new ListNode(67);
ListNode node1 = new ListNode(0);
ListNode node2 = new ListNode(24);
ListNode node3 = new ListNode(58);
node.next = node1;
node1.next = node2;
node2.next = node3;
// 非递归
System.out.println("非递归~~~");
ArrayList<Integer> res = printListFromTailToHead(node);
for (int val : res) {
System.out.println(val);
}
// 递归
System.out.println("递归~~~");
ArrayList<Integer> res1 = printListFromTailToHead1(node);
for (int val : res1) {
System.out.println(val);
}
}
}
【每日寄语】 方向对了,就不怕路远。坚持不仅是一种品质,也是一种信念。
最新文章
- Easyui datagrid加载本地Json数据,CGI数据
- JavaScript数字精度丢失问题总结
- 微信小程序-画布组件
- PhotoKit框架介绍及使用
- pthread_cond_wait的原子性
- Java Socket Option
- linux tar.gz zip 解压缩 压缩命令
- Android Studio 1.3新版体验
- [NOIP2011]瑞士轮
- UNion ALL 和 UNION 的区别
- (转)GBDT迭代决策树理解
- uva208
- Spring系列(零) Spring Framework 文档中文翻译
- 学习笔记TF064:TensorFlow Kubernetes
- 【audio】耳机插拔 线控按键识别流程【转】
- XXS level6
- bzoj 2809 可并堆维护子树信息
- BZOJ 3190 赛车 | 计算几何
- ROS 禁止公网暴力破解SSH FTP
- 集合遍历(Set,List,Map)
热门文章
- python 统计工作簿中每个人名出现的次数
- Nginx日志管理
- python习题_读写csv格式的文件
- 设置redis能远程访问
- AtCoder Beginner Contest 146_E - Rem of Sum is Num
- ApacheCN 深度学习译文集 20210125 更新
- C++中的常见错误
- Python—经典练手题目汇总
- python进阶(24)Python字典的底层原理以及字典效率
- 怎么实时同步java虚拟机与操作系统时区 及JVM启动后再更改操作系统时区或时间也能保持其同步? new date() 时差8个小时的解决方案