C++ Write a method deleteValue that deletes all the nodes in the list with the s
ID: 3745343 • Letter: C
Question
C++
Write a method deleteValue that deletes all the nodes in the list with the specified value. The method you write will take a reference to the head of the list and the specified value as input. It will return the head of the list.
There is a Node class provided, and a main method that creates the list as specified in the test case input, calls the deleteValue method and prints the resulting 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:
Sample Input 5:
Sample Output 5:
Sample Input 6:
Sample Output 6:
Explanation / Answer
Node *DeleteValue(Node *head_ref, int key)
{
Node* temp = head_ref, *prev;
while (temp != NULL && temp->data == key)
{
head_ref = temp->next;
free(temp);
return head_ref;
}
while (temp != NULL)
{
while(temp!=NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}
if (temp == NULL)
{
return head_ref;
}
prev->next = temp->next;
free(temp);
temp=prev->next;
}
return head_ref;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.