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

递归

/**
 * 剑指 Offer 06. 从尾到头打印链表
 * 思路:递归或栈
 * */
public class Solution {
    public int[] reversePrint(ListNode head) {
        return reverse(head, 0, null);
    }

    private int[] reverse(ListNode node, int count, int[] result) {
        if (node == null) {
            return new int[count];
        }
        result = reverse(node.next, count + 1, null);
        result[result.length - count - 1] = node.val;
        return result;
    }
}

public class Solution2 {
    public int[] reversePrint(ListNode head) {
        Deque<Integer> stack = new ArrayDeque<>();
        ListNode node = head;
        while (node != null) {
            stack.push(node.val);
            node = node.next;
        }
        return toArray(stack);
    }

    private int[] toArray(Deque<Integer> stack) {
        int[] array = new int[stack.size()];
        for (int i = 0; i < array.length; i++) {
            array[i] = stack.pop();
        }
        return array;
    }
}
posted @ 2022-06-24 20:20  廖子博  阅读(17)  评论(0编辑  收藏  举报