从尾到头打印链表

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

 1 # -*- coding:utf-8 -*-
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # 返回从尾部到头部的列表值序列,例如[1,2,3]
 9     def __init__(self):
10         self.result = []
11         
12     def track(self,listNode):
13         if listNode.next:
14             self.track(listNode.next)
15         self.result.append(listNode.val)
16             
17     def printListFromTailToHead(self, listNode):
18         if listNode:
19             self.track(listNode)
20         return self.result
21         # write code here


leetcode地址,Java版代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public int[] reversePrint(ListNode head) {
11         Stack<Integer> stack = new Stack<>();
12         int len = 0;
13         while (head != null) {
14             stack.add(head.val);
15             head = head.next;
16             len++;
17         }
18         int[] ret = new int[len];
19         int i = 0;
20         while (!stack.isEmpty()){
21             ret[i++] = stack.pop();
22         }
23         return ret;
24     }
25 }