题目:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解答:
/** * public class ListNode { * int val; * ListNode next = null; * <p> * 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<Integer>(); Stack<Integer> stack = new Stack<Integer>(); int element = 0; // 入栈 while (listNode != null) {/*链表不为空:listNode != null*/ stack.push(listNode.val); listNode = listNode.next; } // 出栈 while (!stack.isEmpty()) {/*栈不为空:stack.isEmpty()*/ element = stack.pop(); arrayList.add(element); } return arrayList; } }
来源:https://www.cnblogs.com/mq2020/p/12650764.html