题目描述
输入一个链表,从尾到头打印链表每个节点的值。
分类:链表,栈
分类:链表,栈
解法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> stack = new Stack<Integer>();
ListNode p = listNode;
while(p!=null){
stack.add(p.val);
p = p.next;
}
ArrayList<Integer> arr = new ArrayList<Integer>();
while(stack.size()!=0){
arr.add(stack.pop());
}
return arr;
}
}