[英]Remove String node from single linked list java
您好,我正在學習單鏈列表,並且正在使用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
實際上是非null的):
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.