从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

解题思路:先入栈相当于链表逆序再出栈实现链表从尾到头的顺序输出。

 1 /**
 2 *    public class ListNode {
 3 *        int val;
 4 *        ListNode next = null;
 5 *
 6 *        ListNode(int val) {
 7 *            this.val = val;
 8 *        }
 9 *    }
10 *
11 */
12 import java.util.*;
13 public class Solution {
14     public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
15         if(listNode == null){
16             return new ArrayList();
17         }else{
18             ArrayList<Integer> arr = new ArrayList<Integer>();
19             Stack<Integer> ss = new Stack<Integer>();
20             while(listNode!=null){
21                 ss.push(Integer.valueOf(listNode.val));
22                 listNode = listNode.next;
23             }
24             while(!ss.empty()){
25                 arr.add(ss.pop());
26             }
27             return arr;
28         }
29     }
30 }

注意:new ArrayList()与 NULL 不相等

  ArrayList源码中默认初始的容量为10
  private static final int DEFAULT_CAPACITY = 10;

ps:源码很重要。。。还是要加油!!!

原文地址:https://www.cnblogs.com/haq123/p/12094365.html