题目:
https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题解:
一说到链表题,我们第一就会想到迭代算法和递归算法,但是看下本题的要求,是从尾到头打印链表,就不需要搞一个新的链表,所以迭代算法可以先pass掉,因此我们优先考虑递归,可以不断寻找链表的Next,直到Next为null,然后不断向上返回值。
图解:
代码:
链表类:
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
算法:
public class Solution {
/**
* 临时数组
*/
ArrayList<Integer> tmp = new ArrayList<>();
public int[] reversePrint(ListNode head) {
//先进行递归
recur(head);
int[] res = new int[tmp.size()];
//将List的值传给int数组
for (int i = 0; i < res.length; i++) {
res[i] = tmp.get(i);
}
return res;
}
/**
* 递归方法
*
* @param head
*/
public void recur(ListNode head) {
//递归的终止条件
if (head == null) {
return;
}
//进行递归
recur(head.next);
tmp.add(head.val);
}
}
测试:
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
listNode.next = new ListNode(3);
listNode.next.next = new ListNode(2);
Solution solution = new Solution();
int[] ints = solution.reversePrint(listNode);
for (int i : ints) {
System.out.println(i);
}
}