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");
}
}
I have this code in a method called dropClass
it is supposed to remove the node from the
linked list and it works but when I try to print it in toString
I get stuck in an infinite
loop, I found the line of code is follow.setNext(current);
that seems to be the cause of the
infinite loop but I dont know what to do to fix, if I take it out it doesn't remove the
node buts prints correctly, here is where the infinite loop is happening
//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;
}
}
the loop starts after while(current != null)
, it works perfectly if I don't remove a node can some one explain what I did wrong when removing the node?
Edit:the setNext methods body
public void setNext(Node next)
{
this.next = next;
}
also the loop i'm using to print out the linked lists
for(int j = 0;j<list.length;j++)
{
one = list[j];
System.out.println(one);
}
I should also mention all the linked lists are in an array call list