从尾到头打印链表

题目描述:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

实现语言: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) {
        ArrayList<Integer> res=new ArrayList<Integer>();
        if(listNode==null){
            return res;
        }
        Stack<Integer> stk=new Stack<Integer>();
        ListNode cur=listNode;
        while(cur!=null){
            stk.push(cur.val);
            cur=cur.next;
        }
        while(!stk.isEmpty()){
            res.add(stk.pop());
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xidian2014/p/10189583.html