1.题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
2.解题思路
-
先用一个栈stack存储从头到尾的链表数值
-
再依次弹出,因为栈是先进后出的,故弹出的结果为从尾到头
-
将弹出的结果放入list返回
3.代码
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;
}
}
}