为什么这段java代码不起作用?

发布于 2024-08-17 18:51:59 字数 599 浏览 1 评论 0原文

我有这个代码片段

class bst {
  public node root=null;

  bst() {
    root=null;
  }

  public void insert(int data) {  
    insert(this.root,data);
  }

  private void insert(node ro,int data) {
    if (ro==null) {
      print ("root is null");
      ro=new node(data);
    } else if (data>ro.data)
      insert(ro.right,data); 
    else
      insert(ro.left,data);
  }

  private void print (String str) 
  {
    System.out.println(str);
  }
}

当我调用像 insert(5); 这样的 insert 函数时, insert(8); 它总是打印 root is null

有什么问题吗?

I have this code fragment

class bst {
  public node root=null;

  bst() {
    root=null;
  }

  public void insert(int data) {  
    insert(this.root,data);
  }

  private void insert(node ro,int data) {
    if (ro==null) {
      print ("root is null");
      ro=new node(data);
    } else if (data>ro.data)
      insert(ro.right,data); 
    else
      insert(ro.left,data);
  }

  private void print (String str) 
  {
    System.out.println(str);
  }
}

When I call the insert function like insert(5); insert(8); it alwaty prints root is null.

whats the problem??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漫漫岁月 2024-08-24 18:51:59

您的问题是 insert 方法中的 ro 变量只是对 bst.ro 引用的副本。这意味着,如果您在方法内重置ro变量,则引用的副本将指向newro,原来传递的对象将保持不变。

您的问题是参数传递常见问题解答中的第 1 个问题。我自己已经不止一次回答过这个问题了。 查看一下

Your problem is that ro variable inside the insert method is just a copy of the reference to bst.ro. Meaning that if you reset the ro variable inside the method, just the copy of the reference will point the new ro, the originally passed object will remain the same.

Your question is the top 1 of Parameter Passing FAQ. I myself already answered this question more than once. Check it out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文