Circular linked list head doesn't update when inserting at position 0?

56 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

Your if (position == 0) path:

  • Sets the 'next' of the newly created node to point at what used to be the first node in the list.
  • Sets the 'global' pointer to the first node in the list to this newly created object.

That's literally the two lines you have in there. You ask:

I noticed that the head reference of the last node still shows to the old head. Why does it happen?

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:

someNode.next = head;

That is not a mathematical aliasing concept. That statement doesn't mean: "head and someNode.next are to be deemed as aliases; they are the same, now and forever". No, it just means: "Take the current value of the head variable, and update the value of the next field in whatever object the current value of someNode 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.