调用SLNode <e> find()方法</e>

时间:2011-09-22 15:02:27

标签: java singly-linked-list

我正在为学校提供一个SinglyLinkedList类的作业,我们应该创建一个程序来调用这个类来添加,删除,查找和显示列表中的项目。我已经实现了添加,删除和显示方法,但我无法弄清楚如何调用find方法。任何帮助都会很棒。

以下是我需要实现的SinglyLinked类的方法:

private SLNode<E> find( E target ) {
SLNode<E> cursor = head.getSuccessor();

while ( cursor != tail ) {
  if ( cursor.getElement().equals( target ) ) {
    return cursor; // success
  }
  else {
    cursor = cursor.getSuccessor();
  }
}

return null; // failure

}

这就是我所拥有的......我也包括了其他方法的实现:

public static void addPet()
{
    Scanner keyboard = new Scanner(System.in);      
    System.out.print("\nPlease enter your pet's name and what type of \n    animal it is(i.e. \"Mickey, Mouse\"): \n");
    petType = keyboard.nextLine();
    pet.add(petType, 0);
    System.out.printf("%s was added to the list.\n\n", petType);        
}

public static void displayPets()
{       
    int i;
    for(i=0; i<pet.getLength(); i++)
    {
        System.out.printf("\n%d.\t%s",i+1, pet.getElementAt(i));
    }
    System.out.print("\n\n");
}

public static void deletePet()
{
    int i;
    int j;
    int k;
    String a;
    for(i=0; i<pet.getLength(); i++)
    {
        System.out.printf("\t%d. %s\n",i+1, pet.getElementAt(i));
    }
    System.out.println();
    System.out.printf("\nPlease enter the number of the item to delete: \n");
    Scanner input = new Scanner(System.in);
    j = input.nextInt();
    System.out.printf("%s was deleted from the list.\n\n", pet.getElementAt(j-1));
    pet.remove(j-1);
}

public static void findPet()
{
    String keyword;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter a search term: ");
    keyword = keyboard.nextLine();
    //.find(keyword);
}

我相信我会踢自己,因为它比我做的更简单,但我真的只是卡住了。

1 个答案:

答案 0 :(得分:0)

您的列表显然包含宠物,由某种宠物类型(看起来像String)表示。因此find期望您在addPet中添加类似的宠物类型。并返回包含找到的宠物的SLNode(如果有的话)。由于你还没有发布SLNode,我不知道如何获取其中包含的元素,但是在它上面调用getElement()看起来是一个安全的赌注:-)所以你需要检查值由find返回,null。如果不是null,您可以例如获取其中包含的元素并打印出来。

我想这应该足以让你编写代码;如果不清楚,请发表评论。

相关问题