剑指offer —— 从尾到头打印链表
2024-10-21 03:35:44
1.问题:输入一个链表,从尾到头打印链表每个节点的值。
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { }
}
2.思路:①使用递归
②使用迭代之后再反转 list
③使用 Stack , 利用它的 LIFO(后进先出) 的特性(前提是允许使用 Stack)
3.代码:
①:使用递归
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> result = new ArrayList<>();
if(listNode != null){
addToList(listNode,result);
}
return result;
} public void addToList(ListNode listNode,ArrayList<Integer> result){
if(listNode.next != null){
getNode(listNode.next,result);
}
//只有在当前节点中没有下个节点的时候才会执行添加方法
result.add(listNode.val);
}
②:使用迭代之后再反转 list
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> tempList = new ArrayList<>(); while(listNode != null){
tempList.add(listNode.val);
listNode = listNode.next;
} ArrayList<Integer> result = new ArrayList<>(tempList.size());
for(int i = tempList.size()-1; i >= 0; i--){
result.add(tempList.get(i));
}
return result;
}
③:使用 Stack , 利用它的 LIFO(后进先出) 的特性
import java.util.Stack;
import java.util.ArrayList;
public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
} ArrayList<Integer> result = new ArrayList<>(stack.size());
while(!stack.isEmpty()){
result.add(stack.pop());
}
return result;
}
}
最新文章
- Stackoverflow/dapper的Dapper-Extensions用法(一)
- Python函数信息
- 搭载hexo+github博客系统
- find the peak value
- Netty4.x中文教程系列(三) ChannelHandler
- The Perfect Stall
- apache 设置404页面
- 获取信息的有关Windows API(最有意思是OpenProcess和GetProcessMemoryInfo)
- Hibernate一对一外键映射
- JavaWeb基础之JdbcUtils工具类2.0
- MySql5.7安装及配置
- 企业级Tomcat部署实践及安全调优
- Mysql5.7数据导出提示--secure-file-priv选项问题的解决方法
- unix文件系统中的硬链接和软连接
- springboot 使用mysql(mybatis)
- 日志系统的 ELK 的搭建
- 【转】Closeable, Readable, Flushable, Appendable
- Selenium IDE 宏 试用 一例
- ubuntu svn rabbitvcs 安装
- poj1850Code