题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//如果链表为空,返回一个空数组
if(head==null) return new int[0];
if(head.next==null) return new int[]{head.val};
List<Integer> list=new ArrayList<Integer>();
addNumbers(head,list);
int[] reverseArray=new int[list.size()];
for(int i=0;i<list.size();i++){
reverseArray[i]=list.get(i);
}
return reverseArray;
}
public void addNumbers(ListNode head,List<Integer> list){
if(head.next!=null) addNumbers(head.next,list);
list.add(head.val);
}
}

本文介绍了一种使用递归方法逆序打印链表元素的算法。通过定义一个辅助方法addNumbers,先递归到链表尾部,再将每个节点的值添加到列表中,最后将列表转换为数组返回。这种方法巧妙地利用了递归的特性,实现了从尾到头的逆序打印。
894

被折叠的 条评论
为什么被折叠?



