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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.