<剑指offer> 第3题

题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值

将链表从头到尾压入栈内,出栈的过程就对应着从尾到头

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

}
原文地址:https://www.cnblogs.com/HarSong13/p/11000722.html