从链接列表中选择某些字符串
我有一个使用节点的linkedList。我按字母顺序打印出来,但现在我试图打印出姓名以用户要求的某个字母开头的人。例如:打印出所有名字以“A”开头的人。我确信这不是迄今为止我所拥有的最好方法,但我只是尝试不同的事情,而且我对链表还很陌生。非常感谢任何提示、建议或提示。
以下是我认为可能有用的内容:
public void findSameStartingLetter(BigNode front, String letter) {
BigNode curr;
curr = front;
String name;
name = curr.dataitems;
String d;
// char c;
while (curr.next != null){
d = name.substring(0, 1);
if (d.equals(letter)) {
System.out.println(d);
curr = curr.next;
// for(int i=0; i < 1; i++) {
// c = letter.charAt(i);
// }
}
}
}
I have a linkedList using nodes. I have it printing out alphabetically but now I'm trying to print out the people whose names begin with a certain letter that the user ask for. For example: printing out all the people whose names begin with an "A". I'm sure this isn't the best way to do this what I have so far but I'm just trying different things out and I'm pretty new to linked list. Any tips or advice or hints are greatly appreciated.
Heres what I think I have that may be useable:
public void findSameStartingLetter(BigNode front, String letter) {
BigNode curr;
curr = front;
String name;
name = curr.dataitems;
String d;
// char c;
while (curr.next != null){
d = name.substring(0, 1);
if (d.equals(letter)) {
System.out.println(d);
curr = curr.next;
// for(int i=0; i < 1; i++) {
// c = letter.charAt(i);
// }
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您需要读取循环内节点上的人员姓名,而不是读取名字然后不再分配该变量。
您还应该检查当前节点是否为空,而不是下一个节点。如果您检查下一个,您将错过列表中的最后一个名字。
另外,请确保列表上的指针移动是在 if 之外完成的,因为我们想要检查下一个节点,无论名称是什么。
除了逻辑之外,看起来你对 java 有点不舒服。要清理您的示例,您可以使用 java 功能在一行上进行定义和赋值。
此外,Java 的字符串有一个 startWith 方法也可以实现这一目的,而不是执行子字符串并比较子字符串。干得好!
It looks like you need to be reading the name of the person on the node within the loop, rather than reading in the first name and then not assigning that variable again.
You also should be checking to see if the current node is null, not the next one. If you check for the next one, you will miss the last name in the list.
Also, make sure the pointer movement on the list is done outside the if, as we want to check the next node regardless of what the name was.
Aside from the logic, it looks like you are a little uncomfortable with java. To clean up your example you can use the java ability to delare and assign values on one line.
Futhermore, rather than doing a substring and comparing the substring, Java's string has a startWith method that should do the trick as well. Nice job!
对我来说看起来很好,我唯一要改变的是使用
equalsIgnoreCase()
而不仅仅是equals()
。哦,将curr = curr.next;
行保留在if
之外Looks fine to me, the only thing I'd change is using
equalsIgnoreCase()
instead of justequals()
. Oh, and leave thecurr = curr.next;
line outside of theif