java - 在递归调用中作为父节点传递的节点未更新

标签 java data-structures

public class LinkedList{
    private class Node{
        int value;
        Node next;
    }
    private Node root;
    public LinkedList(){
        root = null;
    }
    public void insert(int value){
        root = insert(root, root, value);
    }
    public Node insert(Node node, Node parent, int value){
        if(root == null){
            node = new Node();
            node.value = value;
        }else if(node == null){
            node = new Node();
            node.value = value;
            parent.next = null;
        }else{
            node.next = insert(node.next, node, value);
        }
        return node;
    }
    public void printAll(){
        printAll(root);
    }
    public void printAll(Node node){
        Node traverse = node;
        while(traverse != null){
            System.out.println("This node's value is " + traverse.value);
            traverse = traverse.next;
        }
    }
    public static void main(String[] args){
        LinkedList myList = new LinkedList();
        myList.insert(5);
        myList.insert(2);
        myList.printAll();
    }
}

这是一个解释我的麻烦的程序。我有一个插入函数,它同时将当前节点和父节点作为参数。对于第一次插入,我将 5 插入到列表中,根基本上变成了带有 5 的节点。对于第二次插入,我将 2 插入到列表中,但这一次应该将其父节点的 next 设置为 null。

当我在两次插入后打印时,它应该显示

This node's value is 5

但是,它仍然显示父节点的下一个节点仍然链接到第二个节点。

This node's value is 5
This node's value is 2

为什么我的parent.next = null不生效?有没有办法来解决这个问题?我有一个需要能够修改父级的实现。

最佳答案

插入第一个节点时传递 null,null。然后, public Node insert(Node node, Node Parent, int value) 将返回哪个节点。再看一下

public void insert(int value){
        root = insert(root, root, value);
    }

关于java - 在递归调用中作为父节点传递的节点未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35883571/

相关文章:

java - 运行 Spring XML 时构建失败

Java - 套接字编程 - 如何使客户端从多个服务器接收消息?

c++ - 设计容器的技巧

recursion - 返回最大值的树

java - java中如何组合多个正则表达式?

java - 在ant中删除一个文件

java - JWT 在其网站上很容易被解码

reactjs - 如何重构处理太多条件/用例的 react 组件?

java - HashMap的Node中存储hash的目的是什么?

java - 通过递归方法跟踪激活记录