剑指Offer-04从尾到头打印链表

93 阅读1分钟
public static int[] reversePrint(ListNode head){
    int len = 0;
    //用hold保留头结点
    ListNode hold = head;
    //计算链表长度
    while (head != null){
        len++;
        head = head.next;
    }
    int[] res = new int[len];
    //数组倒序存储链表正序
    for (int i = len - 1; i >= 0; i--){
        res[i] = hold.val;
        hold = hold.next;
    }
    return res;
}