The print head from the tail list ---- "prove safety Offer" solution to a problem (Java)

topic

Enter a list of the first node, the return value of a node in order from the head of the tail.

The results returned by the storage array.

Sample
input: [2, 3, 5]
Returns: [5, 3, 2]

Algorithm thinking

The linked list traversal again, saved to a List or Stack, and then iterate over a List or Stack can be.
Time complexity of O (n)

Code

class Solution {
    public int[] printListReversingly(ListNode head) {
        if(head == null) {
            return null;
        }
        
        List<Integer> list = new ArrayList<Integer>();
        ListNode p = head;
        while(p != null) {
            list.add(p.val);
            p = p.next;
        }
        
        int[] resArr = new int[list.size()];
        int resArrCurIdx = 0;
        for(int i=list.size()-1; i>=0; i--) {
            resArr[resArrCurIdx] = list.get(i);
            resArrCurIdx++;
        }
        return resArr;
    }
}

Guess you like

Origin www.cnblogs.com/TatuCz/p/11117218.html