C++ In class, we went over node insertion in detail. Consider a linked list wher
ID: 3846772 • Letter: C
Question
C++
In class, we went over node insertion in detail. Consider a linked list where each node is of the type struct Node, as defined on display 13.7 on page 754. Complete the definition of the function deleteNode (declaration is shown below), that takes as input a pointer to the head of the list, and an integer value. The function should delete all the nodes in the list whose data members have the given value. If there is no node with the given value, the function should not do anything. You can assume that the list will not be empty. If you cannot write out the program function in the space provided below, then print it out on a separate sheet of paper and attach that to this homework.
void deleteNode(struct Node*& head, int value);
Explanation / Answer
// code for deleteNode function
void deleteNode(struct Node*& head, int value){
if(head == NULL)
return;
struct Node* temp = *head, *temp2;
// to delete starting nodes with same key value
while (temp != NULL && temp->data == value)
{
*head = temp->next;
free(temp);
temp = *head;
}
// to delete nodes, other than starting nodes, with same key value
while (temp != NULL)
{
while (temp != NULL && temp->data != key)
{
temp2 = temp;
temp = temp->next;
}
if (temp == NULL)
return;
temp2->next = temp->next;
free(temp);
temp = temp2->next;
}
}
*** By starting nodes I mean:
ex: 5->5->5->10-5->3->2->5
Let us say we want to delete nodes with value 5,
first 3 nodes, i am calling them starting nodes as their value is 5 and no other value is between them .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.