您好,我正在学习单向链表,并且正在使用Java书中的一个例子,我正在尝试删除给定字符串值的节点。我已经编码了,但我没有删除任何东西,任何人都可以给我任何建议吗?我已经很沮丧了,因为我不知道我做错了什么。谢谢。
public class LinkedStringLog implements StringLogInterface {
protected LLStringNode log; // reference to first node of linked
// list that holds the StringLog strings
protected String name; // name of this StringLog
public LinkedStringLog(String name)
// Instantiates and returns a reference to an empty StringLog object
// with name "name".
{
log = null;
this.name = name;
}
public void remove(String element){
LLStringNode currentNode;
LLStringNode temporal;
currentNode = log;
temporal = currentNode.getLink();
if(element.equalsIgnoreCase(currentNode.getInfo())){
log = currentNode.getLink();
}
while(currentNode!=null){
if(element.equalsIgnoreCase(currentNode.getInfo())){
temporal.setLink(currentNode.getLink());
}
else{
currentNode.getLink();
temporal = currentNode;
}
}
我猜您正在进入无限循环,因为您没有在while
循环中更新currentNode
变量。
你可能想要这样的东西:
while(currentNode!=null){
if(element.equalsIgnoreCase(currentNode.getInfo())){
//don't you want to update the link of the node before currentNode here?
}
else{
currentNode = temporal; //update currentNode variable
temporal = currentNode.getLink(); //update temporal variable
}
}
你似乎有很多错误。
其中一个主要问题是,在遍历链表时无法维护prevNode
引用,因此无法将列表中的所有项目链接在一起。
另外,您在哪里设置log
到链表的头项?
无论如何,这个版本的remove
可能会更好(只要log
实际上是非空的):
public void remove(String element) {
if (log == null) {
return;
}
LLStringNode currentNode = log;
LLStringNode prevNode = null;
while (currentNode != null) {
LLStringNode nextNode = currentNode.getLink();
if (element.equalsIgnoreCase(currentNode.getInfo())) {
if (currentNode.equals(log)) {
log = nextNode;
}
if (prevNode != null) {
prevNode.setLink(nextNode);
}
} else {
prevNode = currentNode;
}
currentNode = nextNode;
}
}