java - BinarySearchingTree - dll(generic),不知何故我的项目无法添加到我的 adt 中

标签 java generics adt doubly-linked-list

我正在徘徊我做错了什么,有人可以帮助我吗?我正在尝试制作一个通用的 BST,具有 DDL(双向链表)数据结构。问题是我的 ADT 已初始化,因为我的 isEmpty 方法有效,但我的 public addNewElement 起诉 private insert 不起作用。欢迎任何帮助和建议。

界面:

public interface SortedSetBST <type> extends Iterable<type>{
            void addNewElement(Comparable<type> newElement);

    }

ADT:

package adt;

import java.util.Iterator;
import java.util.Iterator;

import interfaces.SortedSetBST;
import exceptions.*;

public class BinarySearchTree <type> implements SortedSetBST<type> {
    BinaryNode <type> root;
    int size;

    @Override
    public void addNewElement(Comparable  <type>  newElement) {
         insert(newElement, root);  
    }

protected BinaryNode  <type> insert( Comparable <type> x, BinaryNode <type>  t ) {
   if( t == null )
       t = new BinaryNode( x );
   else if( x.compareTo( t.element ) < 0 )
       t.left = insert( x, t.left );
   else if( x.compareTo( t.element ) > 0 )
       t.right = insert( x, t.right );
   else
       throw new DuplicateItemException( x.toString( ) );  // Duplicate
   return t;
}
class BinaryNode<type> {
    type element;      // The data in the node
    BinaryNode<type> left;         // Left child
    BinaryNode<type> right;        // Right child

    // Constructors
    BinaryNode( type theElement ) {
        element = theElement;
        left = right = null;
    }   
}

类应用程序

public class App {
    public static void main(String [] args){
        System.out.println("   Main:");
        BinarySearchTree <String> db = new BinarySearchTree<String>();

        if(db.isEmpty() == true){
            System.out.println(".db empty!");
        }
        db.addNewElement("unu");
        db.addNewElement("doi");
        db.addNewElement("trei");
        System.out.println(db.getSize());
    }
}

输出:

   Main:
.db empty!
0

最佳答案

这很清楚。

在“插入”中,您正在检查 t 是否为空。如果是这种情况,您可以使用 BinaryNode 实例初始化参数 t,并认为在首次传入“null”时您也会更新 root。但“null”在 Java 中是“null”,而不是您可能认为的 C 风格地址!

然后你返回这个参数,但是返回值在“addNewElement”中丢失了。

如何正确执行此操作:

if( t == null ) {
   if (root == null){
      root = new BinaryNode(x);
      return root;
   } else {
      t = new BinaryNode( x );
   }
}

关于java - BinarySearchingTree - dll(generic),不知何故我的项目无法添加到我的 adt 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13147338/

相关文章:

android - 在Windows 7上设置Android开发环境

android - Eclipse 不会创建新的 Android Activity 源或布局。尝试过更新和 sdk

java - 从 Map[String,Any] 类型的 Scala 映射中提取值,其中 Any 可以是 Map 本身

java - 为什么复制对象不会影响第一个对象?

java - MongoDB Java 驱动程序聚合框架使用 $match 和 $text $search 但首先需要 $project

generics - 如何获得 PsiField 的通用类型

generics - 什么是 Java 的 Curiously Recurring Generic Pattern 的 Haskell 等价物?

java - 在 IntelliJ 中创建 MimeMessage 可以工作,但卡在 .jar 中

Typescript 2.4.1 和更严格的泛型打破了 typeof/继承

android - parseSdkContent 失败安卓