从尾到头打印链表

题目:

输入一个链表的头节点,从尾到头打印出每个节点的值。

 

解答:

 1 public class Solution {
 2 
 3     public static ArrayList<Integer> PrintListFromTailToHead(ListNode head) {
 4         ArrayList<Integer> res = new ArrayList<Integer>();
 5 
 6         if(head == null) {
 7             return res;
 8         }
 9 
10         Stack<Integer> stack = new Stack<>();
11         ListNode tmp = head;
12 
13         while(tmp != null) {
14             stack.push(tmp.val);
15             tmp = tmp.next;
16         }
17 
18         while(!stack.isEmpty()) {
19             res.add(stack.pop());
20         }
21 
22         return res;
23     }
24 }

 

posted @ 2019-03-04 15:43  林木声  阅读(128)  评论(0编辑  收藏  举报