剑指Offer第三题:从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个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) {
//使用栈将链表的对象逐个压栈
Stack<Integer> stack = new Stack<>();
ArrayList<Integer> res = new ArrayList<>();
if(listNode == null){
return res;
}
//将链表的数据逐个压栈
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
//将栈顶元素逐个添加到list中
while(!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}
}