从尾到头打印链表

题目描述

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

Stack<Integer> mIntegerStack = new Stack<>();
while (listNode != null) {
mIntegerStack.push(listNode.val);
listNode = listNode.next;
}

ArrayList<Integer> mList = new ArrayList<>();

for (; !mIntegerStack.isEmpty(); ) {
mList.add(mIntegerStack.pop());
}
return mList;
}