在链表的末尾插入节点

Cod*_*ogi 7 java recursion recursive-datastructures data-structures

对于这类问题,有一个简单的迭代解决方案.

Node Insert(Node head,int data) {
    Node newNode = new Node();
    newNode.data = data;
    if (head == null) {
        return newNode;
    }
    Node current = head; 
    while (current.next != null) {
        current = current.next;
    }
    current.next = newNode;
    return head;
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好.但我想学习递归并用这种观点看待事物.因此我想出了下面的解决方案,看起来很优雅,但我不得不承认这只是直觉和给定的代码有效.我想开发一个用于递归的心理模型,或者至少某种方式来验证我的代码是否正常工作.如何从理论上验证以下解决方案是否有效.

递归版

Node Insert(Node head,int data) {
    // Base case.
    if (head == null) {
        Node newNode = new Node();
        newNode.data = data;
        return newNode;
    }
    // Smaller problem instance.
    head.next = Insert(head.next, data);
    return head;
}
Run Code Online (Sandbox Code Playgroud)

Old*_*eon 1

我会进一步修改代码并删除多个退出点。这允许您推断对列表的影响以及必须返回哪个节点。

Node appendRecursive(Node head, int data) {
    // By default return the same list we were given.
    Node list = head;
    if (list == null) {
        // At end of list or list is empty.
        list = new Node();
        list.data = data;
    } else {
        // Recurse.
        head.next = appendRecursive(head.next, data);
    }
    return list;
}
Run Code Online (Sandbox Code Playgroud)

就推理而言,通常需要使用归纳法。

  • 如果列表为空 ( list == null),则创建一个新节点,该节点将成为您的列表。
  • 如果列表不为空,则新列表必须是附加了新数据的列表。

鉴于上述情况,可以推断在所有情况下这都会正确运行,因为列表要么为空,要么不是。

在列表上使用递归通常被认为是低效且笨拙的,因为迭代算法更适合线性结构。更好的练习是编写自己的Tree结构,因为树非常适合递归算法。您会发现在树上递归地执行所需的函数通常更容易、更优雅。

static class Tree {

    Node head = null;

    class Node {

        Node left;
        Node right;
        int data;

        private Node(int data) {
            this.data = data;
        }
    }

    void insert(int data) {
        head = insert(head, data);
    }

    private Node insert(Node node, int data) {
        if (node == null) {
            // Empty tree becomes just the node.
            return new Node(data);
        } else {
            // Pick the correct branch to add this data to.
            if (data < node.data) {
                node.left = insert(node.left, data);
            } else {
                node.right = insert(node.right, data);
            }
        }
        return node;
    }

    private CharSequence toString(Node n) {
        StringBuilder s = new StringBuilder();
        if (n != null) {
            // First print the tree on the left.
            if (n.left != null) {
                s.append(toString(n.left)).append(",");
            }
            // Then the data in this node.
            s.append(n.data);
            // Then the tree on the right.
            if (n.right != null) {
                s.append(",").append(toString(n.right));
            }
        }
        return s;
    }

    @Override
    public String toString() {
        // Even toString is recursive.
        StringBuilder s = new StringBuilder("{");
        s.append(toString(head));
        return s.append("}").toString();
    }
}

public void test() {
    Tree tree = new Tree();
    for (int i : new int[]{6, 5, 4, 3, 2, 1}) {
        tree.insert(i);
    }
    System.out.println(tree);
}
Run Code Online (Sandbox Code Playgroud)

请注意,判断在toString方法中的何处添加“,”是多么简单——这是打印列表时众所周知的笨拙问题。