从尾到头打印列表

从尾到头打印列表

要求:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
方法一:
创建一个栈,先将数组中的元素存储到栈中,再将栈中元素取出放到一个新的数组中。

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> list=new ArrayList<>();
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        return list;
    }
}

方法二:递归

public class Solution {
    ArrayList<Integer> arrayList=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode!=null){
            this.printListFromTailToHead(listNode.next);
            arrayList.add(listNode.val);
        }
        return arrayList;
    }
}  

猜你喜欢

转载自blog.csdn.net/qq_24692885/article/details/84314404