剑指 Offer 06. 从尾到头打印链表

虽然很快做出来,但是性能并不好;

用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;
    }

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13445496.html