题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
代码一、
自己写的:先反转链表,接着从前向后打印。时间复杂度O(n)
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ListNode cur = reverse(listNode);
ArrayList<Integer> list = new ArrayList<Integer>();
while(cur != null){
list.add(cur.val);
cur = cur.next;
}
return list;
}
public ListNode reverse(ListNode cur){
ListNode first = null,next = null;
while(cur != null){
next = cur.next;
cur.next = first;
first = cur;
cur=next;
}
return first;
}
}
代码二、利用栈后进先出的性质,时间复杂度O(n)
注意:使用栈先导入相关包。
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
代码三、递归
递归的本质是方法的压栈,也是后进先出。下面代码1和2顺序很重要。试想一下,把代码中的1和2调换,结果就会完全变了。时间复杂度O(n)
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode != null){
printListFromTailToHead(listNode.next); //1
this.list.add(listNode.val); //2
}
return list;
}
}