I have a circular linked list created. I originally insert all the information to the end.
My insertAtEnd method.
public void insertAtEnd(Card data) {
Node newNode = new Node(data);
if (head == null) {
newNode.next = newNode;
head = newNode;
} else {
Node current = head;
do {
current = current.next;
} while (current.next != head);
newNode.next = head;
current.next = newNode;
}
}
Everything outputs fine then, but when I try to use insertAtPos method while inserting into position 0, an infinite loop happens for some reason. While debugging, I noticed that the head reference of the last node still shows to the old head. Why does this happen?
My insertAtPos method
public void insertAtPos(Card data, int position) {
if (position < 0) {
System.out.println("Invalid position. Position cannot be negative");
return;
}
Node newNode = new Node(data);
if (position == 0) {
newNode.next = head;
head = newNode;
} else {
Node current = head;
int currentIndex = 0;
while (current != null && currentIndex < position - 1) {
current = current.next;
currentIndex++;
}
if (current == null) {
System.out.println("Position is out of bounds");
return;
}
newNode.next = current.next;
current.next = newNode;
}
}
Head is a global variable in that class, so I guess it shouldn't be problem that some methods can or can't edit it?
Your
if (position == 0)
path:That's literally the two lines you have in there. You ask:
The answer is the rather obvious: Because.. you didn't change it.
Possibly you're confused about how java works. It's not like math. When you write something like:
That is not a mathematical aliasing concept. That statement doesn't mean: "
head
andsomeNode.next
are to be deemed as aliases; they are the same, now and forever". No, it just means: "Take the current value of thehead
variable, and update the value of thenext
field in whatever object the current value ofsomeNode
is pointing to to be the same value; they are not equivalent and updating either one later does not magically modify the other one".So, you'd have to go find the last node in the chain (with a loop of some sort) and tell it that its
.next
should be the newly created node.