剑指offer4J【C2 P6】倒序打印链表

题目

倒序打印链表

题解

  1. 递归
    int size = 0;
    int index = 0;
    int [] data;
    public int[] printDesc(ListNode root) {
        visit(root);
        return data;
    }
    private void visit(ListNode root){
        if(root==null){
            data = new int[size];
            return;
        }
        size++;
        visit(root.getNext());
        data[index++] = root.getValue();
    }
  1. 非递归方式 我们使用栈即可
    public int[] printDescByStack(ListNode root) {
        Deque stack = new LinkedList<>();

        while (root != null) {
            stack.push(root.getValue());
            root = root.getNext();
        }
        int []res = new int[stack.size()];
        int index = 0;
        while (!stack.isEmpty()){
            res[index++]=stack.pop();
        }
        return res;
    }

源码: 剑指offer4J

你可能感兴趣的:(剑指offer4J【C2 P6】倒序打印链表)