Junior — Middle
Kuidas lisada uus sõlm seotud nimekirja keskossa?
sobes.tech AI
Vastus AI-lt
To add a new node in the middle of a linked list in Java, you need to:
- Create a new node with the required value.
- Find the node after which you want to insert the new node (for example, by index or 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 simple 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;
}
This way, the new node is inserted between prevNode and prevNode.next.