剑指offer_8 从尾到头打印链表

一、题目描述

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

二、题解

方法一:

可以遍历这个链表,遍历过程中用一个ArrayList保存里面的值,然后再从尾到头遍历这个ArrayList,存储在新的ArrayList里面返回。

//使用另外一个ArrayList存储链表的方法
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList<Integer> list=new ArrayList<Integer>();
            ListNode head=listNode;
            while(head!=null) {
                list.add(head.val);
                head=head.next;
            }
            ArrayList<Integer> result=new ArrayList<Integer>();
            for(int i=list.size()-1;i>=0;i--) {
                result.add(list.get(i));
            }
            return result;
}

方法二:

“后进先出”,这时候就可以联想到栈这个数据结构。
Stack类是Vector类的子类.Vector类与ArrayList类的区别是,Vector是线程安全的,即在多线程的情况下,允许多个线程同时修改vector,但ArrayList是线程不安全的,需要在代码里保证其同步性,即一次只能有一个线程访问ArrayList.所以Vector的性能是比ArrayList要低的。

public static ArrayList<Integer> printListFromTailToHeadWithStack(ListNode listNode) {
        Stack<Integer> stack = new Stack<Integer>();
        ArrayList<Integer> list=new ArrayList<Integer>();
        ListNode head=listNode;
        while(head!=null) {
            stack.push(head.val);
            head=head.next;
        }
        while(!stack.isEmpty()) {
            Integer item=stack.pop();
            list.add(item);
        }
        return list;
}

方法三:
由栈又很容易联想到递归。

链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
来源:牛客网

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;
    }
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值