剑指 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;
    }

 

posted @ 2020-08-06 12:11  欣姐姐  阅读(72)  评论(0编辑  收藏  举报