輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
阿新 • • 發佈:2017-09-07
鏈表
/* * 思路:將鏈表中的值一個一個取出來,壓入一個棧中,然後彈出,就是從後到前的打印了 */ public class PrintLinked { public static void main(String[] args) { System.out.println(printListFromTailToHead(new ListNode(1))); } public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { Stack<Integer> stack = new Stack<Integer>(); while(listNode != null) { stack.push(listNode.val); listNode = listNode.next; } ArrayList<Integer> arr = new ArrayList<>(); while(!stack.empty()) { arr.add(stack.pop()); } return arr; } }
本文出自 “12212886” 博客,請務必保留此出處http://12222886.blog.51cto.com/12212886/1963291
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。