Complete the code to check if the position is valid before deletion.
if (position < 1 || position > [1]) { return head; }
We use a helper function CountNodes(head) to count the total nodes and check if the position is valid.
Complete the code to delete the head node when position is 1.
if (position == 1) { Node temp = head; head = [1]; temp = null; return head; }
To delete the head node, we move the head pointer to the next node.
Fix the error in the loop that moves to the node before the one to delete.
Node current = head; for (int i = 1; i < [1] - 1; i++) { current = current.next; }
The loop should run until the node before the position, so it runs position - 1 times. Using i < position - 1 is correct.
Fill both blanks to unlink the node at the given position.
Node temp = current.next; current.next = temp.[1]; if (temp.[2] != null) { temp.next.prev = current; }
We set current.next to temp.next to unlink the node. Then check if temp.next is not null before updating its prev pointer.
Fill all three blanks to complete the delete function for a doubly linked list.
public Node DeleteAtPosition(Node head, int position) {
if (position < 1 || position > [1]) return head;
if (position == 1) {
Node temp = head;
head = head.[2];
if (head != null) head.[3] = null;
temp = null;
return head;
}
Node current = head;
for (int i = 1; i < position - 1; i++) {
current = current.next;
}
Node tempNode = current.next;
current.next = tempNode.next;
if (tempNode.next != null) {
tempNode.next.prev = current;
}
tempNode = null;
return head;
}The first blank checks the list length using CountNodes(head). The second blank moves head to the next node. The third blank sets the new head's previous pointer to null.
