輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
/**
* 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) {
ListNode tempNode = listNode;
Stack<ListNode> stack = new Stack<ListNode>();
ArrayList<Integer> arr = new ArrayList<Integer>();
if(tempNode==null) return arr;
while(tempNode!=null){
stack.push(tempNode);
tempNode = tempNode.next;
}
while(!stack.isEmpty()){
arr.add((Integer)stack.pop().val);
}
return arr;
}
}