captaincabbage
captaincabbage

Reputation: 1

How do you insert elements into a circular singly linked list in Java?

I was looking at the following code for insertion of a node at the beginning of a circular linked list, but I am still very confused by the logic of how this is done. I understand the part where if a list is empty you can just equate the new node to the list's head, but I really do not understand how all the nodes are 'shifted around' (I know that that's not quite how linked lists work, but so to speak) so that there is room for a new node and why you need a new dynamic node. Credit: https://www.geeksforgeeks.org/circular-singly-linked-list-insertion/

static Node addBegin(Node last, int data)
{
    if (last == null)
        return addToEmpty(last, data);
   
      // Creating a node dynamically
    Node temp = new Node();
      
      // Assigning the data
    temp.data = data;
   
      // Adjusting the links
    temp.next = last.next;
    last.next = temp;
  
    return last;
}

Upvotes: 0

Views: 105

Answers (1)

Vavaste
Vavaste

Reputation: 169

The nodes are not "Shifted around", imagine it like a chain (the one used to lock the gates), you go to disassemble a node of the chain, insert a new one and link the new node (temp) with the old node ) that was connected to the disessembled one (temp.next=last.next), then you link the old node of the chain ("last" in the code) with the new inserted node (temp) (last.next=temp)

Upvotes: 1

Related Questions