0

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

这是我需要实现的 SingleLinked 类的方法:

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);
}

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

4

1 回答 1

0

Your list apparently contains pets, represented by some pet type (which looks like a String). So find expects a similar pet type you added in addPet. And returns an SLNode containing the found pet, if there is one. Since you haven't posted SLNode, I can't tell how to get the element contained in it, but calling getElement() on it looks like a safe bet :-) So you need to check the value returned by find, for nullness. If it's not null, you can e.g. get the element contained in it and print it.

I suppose this should be enough for you to write the code; if it's not clear, please comment.

于 2011-09-22T15:17:40.400 回答