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:
- Create a new node with the desired value.
- Find the node after which you want to insert the new node (for example, by index or by value).
- 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.