I've been struggling to figure out why this code is stuck in an infinite loop. The back story is I have found the solution, I changed the constructor to assign head is equal to null and that fixed it.
I wonder why this code is NOT working.
When I add different nodes, it is working. The code works as expected.
Issues arise when adding the same node.
public class Main {
public static void main(String[] args) {
Node one = new Node(1);
Node two = new Node(2);
LinkedList list = new LinkedList(one);
// this gives error, if i add the same nodes
list.add(two);
list.add(two);
System.out.println("Printing out:\n" + list.toString() +"\n");
}
}
public class LinkedList {
Node head;
int length = 0;
public boolean isEmpty() {
return (head==null);
}
public String toString() {
Node current = head;
String string = "Head: ";
while(current.next != null) {
string += current.toString() + " --> ";
current = current.next;
}
string += current.toString() + " --> " + current.next;
return string;
}
public LinkedList(Node node) {
// if were to set head to null and no arg, it works fine
head = node;
length = 1;
}
public void add(Node node) {
if(isEmpty()) {
System.out.println("Empty list, adding node...");
head = new Node(node.data); ++length;
return;
}
else {
Node current = head;
while(current.next != null) {
current = current.next;
}
//current.next = new Node(node.data);
current.next = node;
++length;
return;
}
}
The error is, it never terminates, hence why I think it is forever looping.
I think in your add(Node node) code. When you adding same node twice, it will point the next to itself. Therefore it would be infinite loop.