题目描述:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:
1.看到逆序,马上想到使用栈呗。
代码
/**
* 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) {
Stack<Integer> s = new Stack<Integer>();
ListNode p = listNode;
ArrayList<Integer> resultArray = new ArrayList<>();
while(p != null) {
s.push(p.val);
p = p.next;
}
while (!s.empty()) {
resultArray.add(s.pop());
}
return resultArray;
}
}