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

题目描述:

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

分析:

  借助栈的先进后出特性。

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(listNode == null) return list;        
        Stack<Integer> stack = new Stack<Integer>();
        while(listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }
        while(!stack.isEmpty()) {
            list.add(stack.pop());
        }      
        return list;        
    }
}
原文地址:https://www.cnblogs.com/zywu/p/5757130.html