我正在做一个学校的作业,其中提供了一个SinglyLinkedList类,我们应该创建一个程序,调用这个类来添加、删除、查找和显示列表中的项目。我已经很好地实现了add、delete和display方法,但是我不知道如何调用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);
}我肯定我会踢自己,因为这比我做的简单,但我真的被卡住了。
发布于 2011-09-22 23:17:40
您的列表显然包含宠物,由一些宠物类型(看起来像String)表示。所以find希望你在addPet中添加一个类似的宠物类型。并返回一个包含找到的宠物的SLNode。因为您还没有发布SLNode,所以我不知道如何获取其中包含的元素,但是在它上调用getElement()看起来像是一个安全的赌注:-)所以您需要检查find返回的值是否为null。如果它不是null,你可以获取其中包含的元素并打印出来。
我想这对你写代码应该足够了;如果不清楚,请评论。
https://stackoverflow.com/questions/7516998
复制相似问题