Complete the code to insert a new node at the given position in the linked list.
Node newNode = new Node(data); if (position == 0) { newNode.next = head; head = [1]; }
To insert at the start, the new node becomes the head.
Complete the loop to reach the node just before the insertion position.
Node current = head; for (int i = 0; i < [1] - 1; i++) { current = current.next; }
We loop until the node before the desired position to insert.
Fix the error in linking the new node to the next node.
newNode.next = [1].next; [2].next = newNode;
The new node's next should point to current's next, then current's next points to new node.
Fill both blanks to check if position is valid and handle empty list.
if (position < 0 || position > [1]) { throw new IndexOutOfBoundsException(); } if (head == [2]) { head = new Node(data); return; }
Position must be within 0 and size. If list is empty (head is null), create new head.
Fill all three blanks to complete the insertAtPosition method.
public void insertAtPosition(int data, int position) {
if (position < 0 || position > [1]) {
throw new IndexOutOfBoundsException();
}
if (position == 0) {
Node newNode = new Node(data);
newNode.next = [2];
head = newNode;
return;
}
Node current = head;
for (int i = 0; i < position - 1; i++) {
current = current.next;
}
Node newNode = new Node(data);
newNode.next = current.[3];
current.next = newNode;
}Check position against size, insert at head if position 0, else traverse and insert by adjusting next pointers.
