从尾到头打印链表

题目

牛客网

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

解题思路

  1. 栈
1. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
2. LinkedList<Integer> stack = new LinkedList<>();

4. while (listNode != null) {
5. stack.addLast(listNode.val);
6. listNode = listNode.next;
7. }

9. ArrayList<Integer> res = new ArrayList<>();

11. while (!stack.isEmpty()) {
12. res.add(stack.pollLast());
13. }

15. return res;
16. }
  1. 递归:当链表过长时,会导致栈溢出
1. public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
2. ArrayList<Integer> res = new ArrayList<>();

4. print(res,listNode);

6. return res;
7. }

9. private void print(ArrayList<Integer> res, ListNode listNode) {
10. if (listNode == null) return;

12. print(res, listNode.next);

14. res.add(listNode.val);
15. }