输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
解决方案:利用栈来完成
import java.util.ArrayList; import java.util.Stack; //利用栈stack public class TailToHead { public static void main(String[] args) { ListNode node1 =new ListNode(10); ListNode node2 =new ListNode(20); ListNode node3 =new ListNode(30); ListNode node4 =new ListNode(40); node1.next=node2; node2.next=node3; node3.next=node4; ArrayList<Integer> list = printListFromTailToHead(node1); for (Integer integer : list) { System.out.println(integer); } } static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> aList = new ArrayList<Integer>(); Stack<Integer> stack = new Stack<Integer>(); // 若链表为空 if (listNode == null) { return aList; } while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.isEmpty()) { aList.add(stack.pop()); } return aList; } }