从尾到头打印链表

题目描述

输入一个链表,按链表从尾到头的顺序返回一个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);
}
}
}

【每日寄语】 方向对了,就不怕路远。坚持不仅是一种品质,也是一种信念。

最新文章

  1. Easyui datagrid加载本地Json数据,CGI数据
  2. JavaScript数字精度丢失问题总结
  3. 微信小程序-画布组件
  4. PhotoKit框架介绍及使用
  5. pthread_cond_wait的原子性
  6. Java Socket Option
  7. linux tar.gz zip 解压缩 压缩命令
  8. Android Studio 1.3新版体验
  9. [NOIP2011]瑞士轮
  10. UNion ALL 和 UNION 的区别
  11. (转)GBDT迭代决策树理解
  12. uva208
  13. Spring系列(零) Spring Framework 文档中文翻译
  14. 学习笔记TF064:TensorFlow Kubernetes
  15. 【audio】耳机插拔 线控按键识别流程【转】
  16. XXS level6
  17. bzoj 2809 可并堆维护子树信息
  18. BZOJ 3190 赛车 | 计算几何
  19. ROS 禁止公网暴力破解SSH FTP
  20. 集合遍历(Set,List,Map)

热门文章

  1. python 统计工作簿中每个人名出现的次数
  2. Nginx日志管理
  3. python习题_读写csv格式的文件
  4. 设置redis能远程访问
  5. AtCoder Beginner Contest 146_E - Rem of Sum is Num
  6. ApacheCN 深度学习译文集 20210125 更新
  7. C++中的常见错误
  8. Python—经典练手题目汇总
  9. python进阶(24)Python字典的底层原理以及字典效率
  10. 怎么实时同步java虚拟机与操作系统时区 及JVM启动后再更改操作系统时区或时间也能保持其同步? new date() 时差8个小时的解决方案