剑指offer 从尾到头打印链表

情到浓时终转凉″ 提交于 2020-01-24 18:57:41

题目

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路1
最简单的方法,直接按顺序遍历,然后利用Collections函数转置。

import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode node) {
        ArrayList<Integer> ans=new ArrayList();
        if(node==null) 
            return ans;
        while(node!=null){
            ans.add(node.val);
            node=node.next;
        }
        Collections.reverse(ans);
        return ans;
    }
}

思路2
因为是倒叙输出,所以利用栈的先进后出的特性。

import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode node) {
        ArrayList<Integer> ans=new ArrayList();
        Stack<Integer> stack=new Stack();
        while(node!=null)
        {
            stack.push(node.val);
            node=node.next;
        }
        while(!stack.isEmpty()){
            ans.add(stack.pop());
        }
        return ans;
    }
}

思路三
递归

import java.util.*;
public class Solution {
        ArrayList<Integer> ans=new ArrayList();
    public ArrayList<Integer> printListFromTailToHead(ListNode node) {
        if(node!=null)
        {
            printListFromTailToHead(node.next);
            ans.add(node.val);
        }
        return ans;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!