从尾到头打印链表

54 阅读1分钟

从尾到头打印链表

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。

样例
输入:[2, 3, 5]
返回:[5, 3, 2]

线性扫描

时间复杂度O(n)

class Solution {
    public int[] printListReversingly(ListNode head) {
        int count = 0;
        ListNode temp = head;

        while(temp!=null){
            temp = temp.next;
            count++;
        }
        int [] reverseArray = new int [count];
        for (int i = count-1 ; i >= 0 ; i-- ){
            if(head != null) {
                reverseArray[i] = head.val;
            }
            head = head.next;
        }
        return  reverseArray;

    }
}