剑指offer-从尾到头打印链表 java实现

题目描述:

输入一个链表,从尾到头打印链表每个节点的值。

代码实现:

/**
*    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>();
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        
        while(listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.empty()){
            arrayList.add(stack.pop());
        }
        return arrayList;
    }
}

备注:无

原文地址:https://www.cnblogs.com/czwangzheng/p/8391183.html