Java编程实现从尾到头打印链表代码实例
作者:lilivian 时间:2021-12-28 12:13:41
问题描述:输入一个链表的头结点,从尾巴到头反过来打印出每个结点的值。
首先定义链表结点
public class ListNode {
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
思路1:此题明显想到是利用栈的思想,后进先出,先遍历链表,依次将结点值进栈。最后在遍历栈出栈。
public static Stack<Integer> printListReverse_Stack(ListNode listNode){
Stack<Integer> stack = new Stack<Integer>();
if(listNode != null){
ListNode p = listNode;
while(p != null){
stack.add(p.val);
p = p.next;
}
}
return stack;
}
思路2:直接遍历链表,按照头插法依次插入ArrayList即可
public static ArrayList<Integer> printListFromTailToHead(ListNode listNode){//表头也存储元素
ArrayList<Integer> print = new ArrayList<Integer>();
if(listNode == null){
return print;
}
int add = 0;
ListNode p = listNode;
while(p != null){
print.add(0, p.val);
p = p.next;
}
return print;
}
思路3:可以使用递归的思想(本质也是栈的思想)
public ArrayList<Integer> printListReversely_Recursively(ListNode listNode){
ArrayList<Integer> print = new ArrayList<Integer>();
if(listNode == null){
return print;
}
print.addAll(printListReversely_Recursively(listNode.next));
print.add(listNode.val);
return print;
}
来源:http://blog.csdn.net/lilianforever/article/details/51830414
标签:java,链表
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解 Corba开发之Java实现Service与Client
2023-09-23 03:42:48
![](https://img.aspxhome.com/file/2023/3/60183_0s.png)
C#四种计时器Timer的区别和用法
2021-10-12 01:31:14
springboot表单提交之validator校验
2023-05-16 23:19:17
![](https://img.aspxhome.com/file/2023/4/81324_0s.png)
Java中对list map根据map某个key值进行排序的方法
2023-09-04 17:10:03
Seata AT模式TransactionHook被删除探究
2022-01-12 14:56:49
![](https://img.aspxhome.com/file/2023/2/63492_0s.png)
Mybatis如何获取最新插入数据的id
2023-02-26 08:15:20
Go Java算法猜数字游戏示例详解
2022-03-02 21:01:50
Java中CyclicBarrier 循环屏障
2021-11-24 08:22:24
![](https://img.aspxhome.com/file/2023/3/76223_0s.png)
Java实现人机猜拳小游戏
2023-10-07 16:11:37
![](https://img.aspxhome.com/file/2023/1/58681_0s.jpg)
Qt之调用C#的动态库的解决方法
2023-07-22 03:42:45
![](https://img.aspxhome.com/file/2023/1/67061_0s.png)
改进c# 代码的五个技巧(一)
2021-07-17 23:49:30
![](https://img.aspxhome.com/file/2023/4/76404_0s.png)
OpenCV图像旋转Rotate的详细介绍
2023-07-01 08:22:27
![](https://img.aspxhome.com/file/2023/2/95522_0s.jpg)
Android ViewDragHelper使用介绍
2023-08-01 04:18:59
![](https://img.aspxhome.com/file/2023/8/85458_0s.gif)
简介Java的Hibernate框架中的Session和持久化类
2023-04-17 14:41:13
java读写二进制文件的解决方法
2022-08-03 14:45:55
C#使用linq对数组进行筛选排序的方法
2023-12-06 06:21:21
Java 中ThreadLocal类详解
2022-01-31 19:58:17
说说@ModelAttribute在父类和子类中的执行顺序
2022-07-31 17:59:55
Springboot集成spring data elasticsearch过程详解
2023-04-16 00:42:16
![](https://img.aspxhome.com/file/2023/4/70484_0s.png)
详解如何让Spring MVC显示自定义的404 Not Found页面
2023-12-12 15:48:47
![](https://img.aspxhome.com/file/2023/1/72571_0s.jpg)