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

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

思路:一开始想的是:用一个List ,动态的记录链表节点的值,但是 List 每一次 add( n ) 耗时太久,而且最后 List 转为 int[ ] 页不方便。

改进思路:利用 2 次遍历,来换取 List 存值、以及最后取值放入 int[ ] 的开销。

class Solution {
    public int[] reversePrint(ListNode head) {
        ListNode tmp = head;
        int count = 0;
        while(tmp != null){
            count++; // 第一次遍历,得到链表节点的个数
            tmp = tmp.next;
        }
        int[] res = new int[count]; //申请同样大小的数组
        while(head != null){
            res[--count] = head.val; // 第二次遍历,往数组里面记录值
            head = head.next;
        }
        return res;
    }
}

  

 从时间上来看,多遍历一次还是划算的。

原文地址:https://www.cnblogs.com/luo-c/p/13648220.html