剑指offer_【3】从尾到头打印链表

1.题目描述

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

2.解题思路

  1. 先用一个栈stack存储从头到尾的链表数值

  2. 再依次弹出,因为栈是先进后出的,故弹出的结果为从尾到头

  3. 将弹出的结果放入list返回

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Main_3 {
public static class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}

public static class Solution {
ArrayList<Integer> arrayList = new ArrayList<Integer>();

public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

Stack<Integer> stack = new Stack<>();
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> list = new ArrayList<>();
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
}
}
文章目录
  1. 1. 1.题目描述
  2. 2. 2.解题思路
  3. 3. 3.代码
| 139.6k