gpt4 book ai didi

java - java删除链表中的节点

转载 作者:行者123 更新时间:2023-12-01 11:18:44 26 4
gpt4 key购买 nike

我要编写一个菜单驱动的程序,它要么接受单词及其含义,要么按字典顺序显示单词列表(即在字典中)。我必须编写的一种方法是删除方法。赋值是基于链表的基本属性。我们实际上并没有使用链表类。这是我到目前为止所拥有的:

public String delete(String a) {
boolean found = false;
WordNode aux = list;
WordNode back = null;
String deleted = "";

while (aux != null && !found) {

if (a.equalsIgnoreCase(aux.getAll().getWord())) {
deleted = deleted + aux.getAll().getWord();

back = aux.next;

aux = null;

found = true;
} else {

back = aux;
aux = aux.next;

}

}
return deleted;
}

但是每当我在主类中调用删除方法,然后调用我的 toString 时,列表都完好无损。删除的单词仍在列表中。

最佳答案

也许是这样的?

public String delete(String a) {
WordNode aux = list;
WordNode back = null;

while (aux != null) {

if (a.equalsIgnoreCase(aux.getAll().getWord())) {

if (back != null) {
//change the pointer from the previous node to the one after the deleted one
back.next = aux.next;
} else {
//first node was found, so modify list to point his successor as the new head
list = aux.next;
}
return a;
} else {
back = aux;
aux = aux.next;
}

}
return ""; //no node was found
}

这应该符合您的契约(Contract),但我会考虑将列表作为参数传递并返回指向头部的指针。

关于java - java删除链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com