public void dropCourse(String c)
{
if(isEmpty())
throw new NoSuchElementException("Empty Schedule");
Node current = firstNode;
Node follow = firstNode;
follow = follow.getNext();
current = current.getNext();
while(!current.getClasses().equals(c) && current != null)
{
follow = current.getNext();
current.setNext(follow.getNext());
follow = null;
}
if(current.getClasses().equals(c))
{
follow.setNext(current);
System.out.println("Class removed");
}
}
我在名为dropClass
的方法中使用此代码,它应该从
链接列表并且它有效,但是当我尝试在toString
中打印时,我陷入了无限的
循环,我发现代码行是follow.setNext(current);
,似乎是
无限循环,但我不知道该怎么做才能修复,如果我把它取出它不会删除
节点buts正确打印,这是无限循环发生的地方
//Reads schedule
public String toString()
{
if(isEmpty())
return " ";
else
{
String s = " ";
Node current = firstNode;
System.out.print("ID:");
System.out.print(current.getId());
current = current.getNext();
while(current != null)
{
s = s + "Class:"
+ current.getClasses()
+ " Section:"
+ current.getSection()
+ " Credits:"
+ current.getCredit()
+ " ";
current = current.getNext();
}
return s;
}
}
循环在while(current != null)
之后开始,如果我不删除一个节点它可以完美地解释我在删除节点时做错了什么吗?
编辑:setNext方法主体
public void setNext(Node next)
{
this.next = next;
}
也是我用来打印链表的循环
for(int j = 0;j<list.length;j++)
{
one = list[j];
System.out.println(one);
}
我还应该提到所有链接列表都在数组调用列表中