3、从尾到头打印链表
1、使用函数list.add(index, “London”)
每次都在index=0处添加一个整数。
运行时间:16 ms, 内存:9400K
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> l1=new ArrayList<Integer>(); ListNode tmp=listNode; while(tmp != null){ l1.add(0,tmp.val); tmp=tmp.next; } return l1; } }
2、使用栈
倒序结构与栈先进后出的特点相匹配,因此可以考虑使用栈来实现。
运行时间:20ms, 占用内存:9424k
import java.util.Stack; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> l1=new ArrayList<>(); ListNode tmp=listNode; Stack stack=new Stack(); while(tmp != null){ stack.push(tmp.val); tmp=tmp.next; } while(!stack.empty()){ l1.add((Integer)stack.pop()); } return l1; } }
PS:1、需要导入栈相关的包;
2、注意类型的匹配,stack默认为object,而l1为Integer类型,所以需要进行转换;或者可以直接创建Integer类型的栈Stack<integer> stack=new Stack();</integer>
3、使用递归
递归的本质就是栈的结构,因此也可以使用递归的方法来实现。
运行时间:17ms, 占用内存:9420k
public class Solution { ArrayList<Integer> l1=new ArrayList<>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ListNode tmp=listNode; if(tmp!=null){ printListFromTailToHead(tmp.next); l1.add(tmp.val); } return l1; } }
PS:l1需要设置为实例变量,而不是方法变量。
关于实例变量、类变量、方法变量:https://www.cnblogs.com/Fanzifeng/p/7181980.html