【发布时间】:2013-11-18 18:59:42
【问题描述】:
所以我有这个充满名字的链表。用户将搜索名称的第一个字母,并打印出名称以字母开头的节点。当我运行它时,它以为我没有得到任何回应。虽然如果我在循环中插入一些打印行,我会得到它们。
这里是:
public String printSection(){
LinkedListNode current = front;
String searchedLetter;
int i = 0;
String retSec = "The nodes in the list are:\n";
//Get the input of the name being removed
Scanner s = new Scanner(System.in);
System.out.println("Enter the first letter of the section you would like to print out");
searchedLetter = s.nextLine();
//while current is not null
while(current != null){
//if the data in current starts with the letter entered for searchedLetter
if(current.getData().startsWith(searchedLetter)){
//if(current.getData().substring(0,1) == searchedLetter){
//Increment the number of the node
i++;
//Print the node(s)
retSec += "Node " + i + " is: " + current.getData() + "\n";
//Traverse the list
current = current.getNext();
System.out.println("You made it here");
}
}
return retSec;
}
}
这里是:(新的工作方法)
public void printSection(){
LinkedListNode current = front;
String searchedLetter;
int i = 0;
//Get the input of the name being removed
Scanner s = new Scanner(System.in);
System.out.println("Enter the first letter of the section you would like to print out");
searchedLetter = s.nextLine();
//while current is not null
while(current != null){
//if the data in current starts with the letter entered for searchedLetter
if(current.getData().startsWith(searchedLetter)){
//Increment the number of the node
i++;
//Print the node
System.out.println("Node " + i + " is: " + current.getData());
}
//Traverse the list
current = current.getNext();
}
}
【问题讨论】:
-
问题可能是您对
front的当前声明,所以首先确保一切正常。然后,查看第二个 while 循环是否真的必要。似乎您只需要第一个来检查您是否还没有到达链表的末尾。 -
您可以将列表转换为 Set,然后使用子集方法。看看这个答案:stackoverflow.com/questions/7228350/…
标签: java search linked-list nodes