输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解题思路:
遍历入栈,出栈进入ArrayList
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.empty()){
arrayList.add(stack.pop());
}
return arrayList;
}
}