gpt4 book ai didi

java - 替换链表中的元素

转载 作者:行者123 更新时间:2023-12-01 18:41:32 25 4
gpt4 key购买 nike

我有一个受邀参加聚会的客人的链接列表。我想用其他人代替其中一位客人。为此,我在列表中搜索要删除的人,将其删除,然后将新人添加到列表的前面。

这是到目前为止我的替换方法:

public void replace(String n, String rn, String rf){
boolean match = false;
GuestNode curr = GuestList;
GuestNode replace = new GuestNode(rn,rf);
GuestNode onemore, twomore;

while (match == false && curr != null){
if (curr.getLink().getName().equals(n)){
onemore = curr.getLink();
twomore = onemore.getLink();
curr.setLink(twomore);
match = true;
}
else
curr = curr.getLink();
}

if (match){
GuestList = curr;
addNode(replace);
System.out.println(n+ " has been replaced with " +rn+ ".");
}
else
System.out.println(n+ " was not found.");
}

我的麻烦是,当我运行它时,我可以找到并删除原来的人,并将新人添加到列表的前面,但它不断丢失其余的内容。这是我得到的输出(用户输入以粗体显示):

Please enter one of the following options: sort, search, replace, delete, print, quit
print

ten is attending, and they like 10 ice cream.
nine is attending, and they like 9 ice cream.
eight is attending, and they like 8 ice cream.
seven is attending, and they like 7 ice cream.
six is attending, and they like 6 ice cream.
five is attending, and they like 5 ice cream.
four is attending, and they like 4 ice cream.
three is attending, and they like 3 ice cream.
two is attending, and they like 2 ice cream.
one is attending, and they like 1 ice cream.

Please enter one of the following options: sort, search, replace, delete, print, quit
replace

Who would you like to delete? three
Who would you like to put in their place, and what is their favorite ice cream flavor?
THIRTYTHREE 33
three has been replaced with THIRTYTHREE.

Please enter one of the following options: sort, search, replace, delete, print, quit
print

THIRTYTHREE is attending, and they like 33 ice cream.
four is attending, and they like 4 ice cream.
two is attending, and they like 2 ice cream.
one is attending, and they like 1 ice cream.

我已经处理这个问题几个小时了,但我找不到错误出在哪里。请帮忙!

编辑:这是我的 GuestNode 的代码,以防问题出在那里。

public class GuestNode{
private String name;
private String fav;
private GuestNode link;

public GuestNode(String n, String f){
this.name = n;
this.fav = f;
link = null;
}

public String toString(){
return this.name +" is attending, and they like "+ this.fav +" ice cream.";
}

public String getName(){ return this.name; }
public String getFav(){ return this.fav; }
public GuestNode getLink(){ return this.link; }
private void setName(String n){ this.name = n; }
private void setFav(String f){ this.fav = f; }
public void setLink(GuestNode l){ this.link = l; }

public void clear(){
this.link = null;
}
}

最佳答案

假设GuestList是第一个节点,问题就在这里:

GuestList = curr;

这会将 curr 设为列表的第一个节点,从而截断列表的开头。

此外,请确保您的代码即使在特殊情况下也能正常工作(如果您想替换第一个节点会发生什么?)

关于java - 替换链表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19796044/

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