Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method Node* add(Node* head, int index, int value) to add a node to a li

ID: 3744996 • Letter: W

Question

Write a method Node* add(Node* head, int index, int value) to add a node to a linked list. The head of the linked list is input, as well as the index where the node should be added and the value associated with the node. The program returns the head of the updated list. If the index is greater than the size of the list, the program should return NULL.

We have defined the following node C++ class for you:


The program input is a value, an index, and a list.

The output is a traversal of the updated list.

Sample Input 1:

Sample Output 1:

Sample Input 2:

Sample Output 2:

Sample Input 3:

Sample Output 3:

Sample Input 4:

Sample Output 4:

Explanation / Answer

Code:


Node* add(Node *head, int index, int value)
{

Node * temp = new Node();
temp->value= -1;
temp->next = head;
Node* node = temp;
int i = 0;
while (node->next && i < index) {
node = node->next;
i++;
}

Node* preNext = node->next;
Node* newNode = new Node();
newNode->value = value;
newNode->next = preNext;
node->next = newNode;
head = temp->next;
delete temp;

return head;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote