java循环单链表删除方法
我需要编写一个程序,将名字存储在循环链表中,然后逐个删除,直到只剩下一个名字。我无法使用删除方法,有人能帮我找出问题所在吗?下面是该方法的代码
public static void delete () throws IOException
{
String loser;
boolean found;
Node temp;
do
{
System.out.println ("Please enter the name of the contestant you want to eliminate");
loser = stdin.readLine ();
head = node;
found = false;
do
{
node = node.next;
if (node.data.equals (loser))
{
found = true;
temp = node;
}
}
while (!node.next.equals (head) || found == false);
if (loser.equals (head))
{
head = node.next;
}
if (found == true)
{
node = node.next;
temp = null;
System.out.println ("Elimination sucessful!");
}
else
{
System.out.println ("This name was not found! Please try again.");
}
System.out.println ("The contestants left are:");
do
{
System.out.println (node.data);
node = node.next;
}
while (!node.next.equals (head));
if (node.next.equals (node))
{
System.out.println ("There is only one contestant left!");
}
}
while (!node.next.equals (node));
}
下面是输入姓名的数字时的输出示例
Please enter the name of the contestant or 'fin' to stop:
1
Please enter the name of the contestant or 'fin' to stop:
2
Please enter the name of the contestant or 'fin' to stop:
3
Please enter the name of the contestant or 'fin' to stop:
4
Please enter the name of the contestant or 'fin' to stop:
5
Please enter the name of the contestant or 'fin' to stop:
fin
Please enter the name of the contestant you want to eliminate
1
Elimination sucessful!
The contestants left are:
5
1
2
3
Please enter the name of the contestant you want to eliminate
3
Elimination sucessful!
The contestants left are:
4
5
1
2
Please enter the name of the contestant you want to eliminate
4
Elimination sucessful!
The contestants left are:
3
4
5
1
Please enter the name of the contestant you want to eliminate
6
# 1 楼答案
你的代码有很多错误。以下几行都做了一些你认为不一样的事情:
什么也不做(充其量)或无限循环。我想它应该将
node
重置为head
,但我不明白为什么什么也不做。事实上,它甚至不应该在没有一个大的警告的情况下编译,这个条件永远不会是真的。这里将比较字符串对象和节点对象。我想如果在这里删除它,您可能会想“修复”
head
不会删除任何内容。它只推进
node
指针。你可能需要一些类似于node.next = node.next.next
的东西,假设node
是失败者temp
的前身,但事实并非如此最后
不打印剩余的参赛者(链表中的节点),只打印从当前光标
node
到“结束”的参赛者。我猜您想从head
迭代到“end”祝你学习顺利。如果你的问题是“家庭作业”,请将其标记为“家庭作业”