虽然很快做出来,但是性能并不好;
用ArrayList做的:
public int[] reversePrint(ListNode head) { ArrayList<Integer> list = new ArrayList<>(); while(head != null){ list.add(0,head.val); head = head.next; } return list.stream().mapToInt(Integer::valueOf).toArray(); }
方法二:
先知道链表长度,初始化数组,填入数组;
public int[] reversePrint(ListNode head) { int count = 0; ListNode node = head; while(node != null){ count++; node = node.next; } int[] nums = new int[count]; for(int i = count-1;i>=0;i--){ nums[i] = head.val; head = head.next; } return nums; }