Sobes.tech
Junior — Middle

How is a new element added to a linked list?

sobes.tech AI

Answer from AI

Adding a new element to a linked list usually occurs as follows:

  1. A new node with the desired value is created.
  2. The new node's link is set to the next element of the list (for example, the current first element).
  3. The head of the list is updated to point to the new node.

Example in Java for a singly linked list:

class Node {
    int data;
    Node next;
    Node(int data) { this.data = data; this.next = null; }
}

class LinkedList {
    Node head;

    void addFirst(int value) {
        Node newNode = new Node(value);
        newNode.next = head;
        head = newNode;
    }
}

Thus, the new element becomes the first in the list, and the others are shifted further.

How is a new element added to a linked list? — Android - sobes.tech