Complete the code to insert a new node at position 3 in a singly linked list.
Node* insertAtPosition(Node* head, int data) {
Node* newNode = new Node(data);
Node* temp = head;
int count = 1;
while (count < [1] - 1 && temp != nullptr) {
temp = temp->next;
count++;
}
newNode->next = temp->next;
temp->next = newNode;
return head;
}To insert at position 3, we stop at position 2 (one before 3) to adjust pointers correctly.
Complete the code to handle insertion at position 1 (head) in the linked list.
Node* insertAtPosition(Node* head, int data, int position) {
Node* newNode = new Node(data);
if (position == [1]) {
newNode->next = head;
head = newNode;
return head;
}
// code for other positions
return head;
}Position 1 means inserting at the head of the list.
Fix the error in the loop condition to avoid null pointer dereference when inserting at a middle position.
while (temp != nullptr && temp->next != nullptr && count < [1] - 1) { temp = temp->next; count++; }
The loop should run until one node before the target position.
Fill both blanks to correctly update pointers when inserting a new node at a given position.
newNode->next = [1]; [2]->next = newNode;
First, newNode points to the next node after temp, then temp points to newNode.
Fill all three blanks to create a function that inserts a node at a specific position in a singly linked list.
Node* insertAtPosition(Node* head, int data, int position) {
Node* newNode = new Node(data);
if (position == [1]) {
newNode->next = head;
head = newNode;
return head;
}
Node* temp = head;
int count = 1;
while (count < [2] - 1 && temp != nullptr) {
temp = temp->next;
count++;
}
newNode->next = [3];
temp->next = newNode;
return head;
}Position 1 means insert at head. Loop runs until node before position. Then newNode points to temp->next.
