Sobes.tech
Junior — Middle

How can a new node be added to the middle of a linked list?

sobes.tech AI

Answer from AI

To add a new node in the middle of a linked list in Java, you need to:

  1. Create a new node with the desired value.
  2. Find the node after which you want to insert the new node (for example, by index or by value).
  3. Change the links so that the new node points to the next node after the found node, and the found node points to the new node.

Example for a singly linked list:

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

// Insert a new node after prevNode
void insertAfter(Node prevNode, int newData) {
    if (prevNode == null) return;
    Node newNode = new Node(newData);
    newNode.next = prevNode.next;
    prevNode.next = newNode;
}

Thus, the new node is inserted between prevNode and prevNode.next.

How can a new node be added to the middle of a linked… - sobes.tech