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;
}
}

最新文章

  1. Stackoverflow/dapper的Dapper-Extensions用法(一)
  2. Python函数信息
  3. 搭载hexo+github博客系统
  4. find the peak value
  5. Netty4.x中文教程系列(三) ChannelHandler
  6. The Perfect Stall
  7. apache 设置404页面
  8. 获取信息的有关Windows API(最有意思是OpenProcess和GetProcessMemoryInfo)
  9. Hibernate一对一外键映射
  10. JavaWeb基础之JdbcUtils工具类2.0
  11. MySql5.7安装及配置
  12. 企业级Tomcat部署实践及安全调优
  13. Mysql5.7数据导出提示--secure-file-priv选项问题的解决方法
  14. unix文件系统中的硬链接和软连接
  15. springboot 使用mysql(mybatis)
  16. 日志系统的 ELK 的搭建
  17. 【转】Closeable, Readable, Flushable, Appendable
  18. Selenium IDE 宏 试用 一例
  19. ubuntu svn rabbitvcs 安装
  20. poj1850Code

热门文章

  1. PAT L3-008. 喊山(BFS)C4 初赛30分
  2. a(+;-;*;/)b-----demo----bai
  3. 如何通过outline为SQL语句指定执行计划
  4. leetcode443
  5. namenode和datanode机制
  6. 反向索引(Inverted Index)
  7. pl/sql对excel数据的导入和导出
  8. pageBean实现分页
  9. ngx-bootstrap使用01 安装ngx-bootstrap和bootstrap及其使用、外部样式引入
  10. js 控制标记样式