why am I getting an endless loop in this implementation of addlast to linkedlist
guys, I'm trying to implement an "addLast" method of a LinkedList; however, I'm getting an endless loop.... could anyone help
Code :
public void addLast(int n)
{
Node p = new Node(n);
if(first == null)
{
p.next = first;
first = p;
}
else
{
Node current = first;
while(current != null)
{
System.out.println("here!");
if(current.next == null)
{
current.next = p;
}
current = current.next;
}
}
}
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
Think about how you are looping...write the process out on paper if you have to....when the current node's next element is null, you set it the the 'p' node. You loop once more, seeing that the current (which is now p) next node is null, so you set it's next element to p (or itself) - hence there will not be a non-null next element again (circular reference)
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
while(current != null)
{
System.out.println("here!");
if(current.next == null)
{
current.next = p;
}
current = current.next;
Ok, so if the next Node is null, then current.next, a.k.a. the next node, is made p. Then after adding p, which it does right away, current.next won't be null, hence an infinite loop.
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
else
{
Node current = first;
while(current.next != null)
{
System.out.println("here!");
current = current.next;
}
current.next = p;
p.next = null;
}
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
Thank you guys, it was so simple as to adding a "break" line
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
to: javapenguin
oh this one is very simple too... I just added a "break" line to mine
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
Quote:
Originally Posted by
javapenguin
else
{
Node current = first;
while(current.next != null)
{
System.out.println("here!");
current = current.next;
}
current.next = p;
p.next = null;
}
is it necessary to assign "p.next = null"?.... it is already null right?
Re: why am I getting an endless loop in this implementation of addlast to linkedlist
Quote:
it is already null right?
Add a println to the code to print out its value before you set it to null to see what its value is.