输入一个链表,从尾到头打印链表每个节点的值。
思路:首先借助一个栈,遍历链表中的每一个值,然后存储到栈中,利用栈的先进后出特点,然后添加到数组中返回。
package demo3; import java.util.ArrayList; import java.util.Stack; public class Main { static class ListNode{ int val; ListNode next = null; ListNode(int val){ this.val = val; } } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); node1.next = node2; node2.next=node3; node3.next = null; ArrayList result = printListFromTailToHead(node1); print(result); } public static void print(ArrayList result){ if (result != null && result.size()>0) { for (int i=0;i<result.size();i++) { System.out.print(result.get(i)+" "); } System.out.println(); } } public static ArrayList printListFromTailToHead(ListNode listNode){ ArrayList array = new ArrayList(); //借助栈 Stack stack = new Stack(); if (listNode == null) { return array; } while (listNode != null) {//节点不为空 stack.push(listNode.val); listNode = listNode.next; } while (!stack.isEmpty()) { array.add(stack.pop()); } return array; } }