我需要编写一个程序,将名称存储在循环链表中,然后逐个删除它们,直到只剩下一个名字。我不能让我的删除方法工作,有人可以帮我弄清楚什么是错的?这是该方法的代码。
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
答案 0 :(得分:0)
您的代码有很多问题。以下几行都不是你认为的那样:
while (!node.next.equals (head) || found == false);
什么都不做(充其量)或无限循环。我想它应该将node
重置为head
,但我不明白为什么。
if (loser.equals (head))
{
...
}
什么都不做。实际上它甚至不应该在没有强烈警告条件永远不会成真的情况下进行编译。您正在将字符串对象与节点对象进行比较。我想你会想要“修复”head
,如果它在这里被删除了。
if (found == true)
{
node = node.next;
temp = null;
System.out.println ("Elimination sucessful!");
}
不删除任何内容。它只是推进node
指针。你可能需要node.next = node.next.next
这里的某些内容,假设node
是失败者temp
的前身 - 它不是。{/ p>
最后......
System.out.println ("The contestants left are:");
do { System.out.println (node.data); node = node.next; }
while (!node.next.equals (head));
不打印剩余的参赛者(链接列表中的节点),而只打印当前光标node
到“结束”的参赛者。我想你想从head
迭代到“结束”。
祝你学习顺利。如果您的问题是“家庭作业”,请标记您的问题。