题目描述
输入一个链表,从尾到头打印链表每个节点的值。
/**
* 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<Integer>();//用栈存储节点元素
ListNode p = listNode;
while(p != null){
stack.add(p.val);
p = p.next;
}
ArrayList<Integer> array = new ArrayList<Integer>();
while(stack.size() != 0){
array.add(stack.pop());//利用栈后进先出的特性倒序存入输入的值
}
return array;
}
}