Junior — Middle
How does adding a new node in the middle of a linked list occur?
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 traversing the list).
- Set the new node's next reference to the next node of the found node.
- Change the found node's next reference to point to the new node.
Example for a singly linked list:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Insert a new node after prevNode
void insertAfter(Node prevNode, int newData) {
if (prevNode == null) {
System.out.println("Previous node cannot be null");
return;
}
Node newNode = new Node(newData);
newNode.next = prevNode.next;
prevNode.next = newNode;
}
Thus, the new node ends up between prevNode and the next node.