Sobes.tech
Junior — Middle

How is the first node in a linked list found?

sobes.tech AI

Answer from AI

In a linked list, the first node is usually stored in a special variable called "head." This variable points to the first element of the list. If the list is empty, then head is null.

Example in Java:

class Node {
    int data;
    Node next;

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

class LinkedList {
    Node head; // first node of the list

    // method to add an element at the beginning
    void addFirst(int data) {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
}

Thus, to get the first node, it is enough to refer to the variable head.