從尾到頭打印鏈表

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。


/**

*    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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章