思路
1.递归;
2.利用Java List的add(int index,Integer element);
3.利用栈的先进后出
4.用Collections.reverse(List<?> list);
答案
1.递归
import java.util.ArrayList; public class Solution { ArrayList<Integer> arrayList = new ArrayList<Integer>(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode != null){ printListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } }
2.利用Java List的add(int index,Integer element)
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> array = new ArrayList<Integer>(); ListNode p = listNode; while(p != null){ array.add(0,p.val); p = p.next; } return array; } }
3.利用栈的先进后出
import java.util.ArrayList; import java.util.Stack; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); Stack stack = new Stack(); while(listNode != null){ stack.push(listNode.val); listNode = listNode.next; } while(!stack.empty()){ arrayList.add((Integer)stack.pop()); } return arrayList; } }
4.用Collections.reverse(List<?> list);
import java.util.ArrayList; import java.util.Collections; public class Solution { public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); while(listNode != null){ arrayList.add(listNode.val); listNode = listNode.next; } Collections.reverse(arrayList); return arrayList; } }