输入一个链表,从尾到头打印链表每个节点的值
class ListNode{ int val; ListNode next = null; public ListNode(int val){ this.val = val; } } public class printListReverse { //从尾到头打印链表 public static ArrayList<Integer> printListReverse(ListNode listNode){ if (listNode==null)return null; Stack<Integer> stack = new Stack<Integer>(); while (listNode!=null){ stack.push(listNode.val); listNode=listNode.next; } ArrayList<Integer> arrayList = new ArrayList<Integer>(); while(!stack.isEmpty()){ arrayList.add(stack.pop()); } return arrayList; } public static void main(String[] args){ ListNode a = new ListNode(1); ListNode b = new ListNode(2); ListNode c = new ListNode(3); a.next=b; b.next=c; ArrayList<Integer> list = printListReverse(a); for (int i=0;i<list.size();i++) { System.out.print(list.get(i) + " "); } } }