3,从尾到头打印链表 剑指offer java实现

解题前的内容复习:
1.链表
在这里插入图片描述
数组:
在这里插入图片描述
2.集合
在这里插入图片描述
3.ArrayList中的方法
在这里插入图片描述 在这里插入图片描述

解题思路
使用递归:
要逆序打印链表 1->2->3(3,2,1),可以先逆序打印链表 2->3(3,2),最后再打印第一个节点 1。而链表 2->3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数,也就是在求解函数中调用自己,这就是递归函数。

public class ListNode {
    int val;
    ListNode next =null;
    ListNode(int val){
        this.val=val;
    }
}

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> ret = new ArrayList<>();
    if (listNode != null) {
        ret.addAll(printListFromTailToHead(listNode.next));
        ret.add(listNode.val);
    }
    return ret;
}

public static void test(){
        ListNode ListNode1 = new ListNode(1);
        ListNode ListNode2 = new ListNode(2);
        ListNode ListNode3 = new ListNode(3);
        ListNode ListNode4 = new ListNode(4);
        ListNode ListNode5 = new ListNode(5);
        ListNode1.next=ListNode2;
        ListNode2.next=ListNode3;
        ListNode3.next=ListNode4;
        ListNode4.next=ListNode5;
        System.out.println("采用递归");
        ArrayList<Integer> ddsfsdf=printListFromTailToHead(ListNode1);

        System.out.println(ddsfsdf);
    }

    public static void main(String[] args) {
        demo6.test();
    }

执行流程:
在demo6.test();打断点。在这里插入图片描述
首先走test代码
走完这代码的流程之后ListNode1.val ListNode1.next ListNode2.val ListNode2.next
ListNode3.val ListNode3.next 都有了值
在这里插入图片描述
在这里插入图片描述
紧接着把ListNode1带入方法
在这里插入图片描述
在下面的方法中:
ListNode=ListNode1

在这里插入图片描述在这里插入图片描述
判断 listNode1 != null
执行 ret.addAll(printListFromTailToHead(listNode1.next));
其中 listNode1.next=listNode2
执行 ret.addAll(printListFromTailToHead(listNode2));
执行 printListFromTailToHead(listNode2)方法
判断 listNode2 != null
执行 ret.addAll(printListFromTailToHead(listNode2.next));
其中 listNode2.next=listNode3
判断 listNode3 != null
执行 ret.addAll(printListFromTailToHead(listNode3.next));
其中 listNode3.next=null
执行 return
然后 执行ret.addAll(printListFromTailToHead(listNode3.next));下面的
ret.add(listNode3.val);
然后 执行ret.addAll(printListFromTailToHead(listNode2.next));下面的
ret.add(listNode2.val);
然后 执行ret.addAll(printListFromTailToHead(listNode1.next));下面的
ret.add(listNode1.val);
此时的ret:已经倒着装进ret
在这里插入图片描述
返回到:
ArrayList ddsfsdf=printListFromTailToHead(ListNode1);
在这里插入图片描述
控制台返回
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值