解题前的内容复习:
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);
控制台返回