输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
java
方法一:递归
public class Solution{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode ){
if(listNode != null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}
方法二:利用栈
import java.util.Arraylist;
import java.util.Stack;
public class Solution{
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack = new Stack<Integer>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
方法三:利用指针
public class Solution {
public ArrayList printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> list=new ArrayList<Integer>();
ListNode pre = null;
ListNode next = null;
while(listNode != null){ //有点晕
next = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = next;
}
while(pre != null){
list.add(pre.val);
pre = pre.next;
}
}
}