C++ *20.1 (Implement remove(T element)) The implementation of remove(T element)
ID: 3597612 • Letter: C
Question
C++
*20.1 (Implement remove(T element)) The implementation of remove(T element) is omitted in Listing 20.2, LinkedList.h. Implement it.
For input use this sentence, which you may code as a constant string:
"DURING the whole of a dull, dark, and soundless day in the autumn of the year, when the clouds hung oppressively low in the heavens, I had been passing alone, on horseback, through a singularly dreary tract of country; and at length found myself, as the shades of the evening drew on, within view of the melancholy House of Usher."
Your test case should show the string after being loaded into a linked list and then again after the word “of” has been removed.
Explanation / Answer
the code for that is as follows :
--------------------------------------------------------------------------------------------------------------------------
/* In this I am assuming Linked List contains nodes of
* user defined type Node. Each node has link to next node
* and it is accessed by next poninter.Each node has a value
* and it is accessed by value variable
*/
template< class T >
void remove( T element){
Node *temp = root -> next ; // temp pointing to next of root node
Node *prev = root; // prev pointing to root node at starting
if( root -> value != element ){ // if root value is equal to element
// it is handled in else block
while( temp != nullptr ){ // looping over until the node is not null
if( temp -> value == element ){ // if temp value is equal to element
prev -> next = temp -> next; // then pointing prev's next to temp's next
delete temp; // delete temp node
}
else{ // prev pointing to temp and temp moving forward
prev = temp;
temp = temp->next;
}
}
}
else{ // if root value is equal to element
temp = root; // making temp to root
root = root -> next; // making root as next of root
delete temp; // delete temp
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
/* hope this helps */
/* if any queries please comment */
/* thank you */
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.