In: Computer Science
Write a remove(E val) method for CircularlyLinkedList
class
This method remove the first occurrence of the node that contains
the val.
Method to remove first occurrence of node that contain val is provided below.
void remove(E val) {
// If head node is null then the list is empty
if(headNode==NULL) {
printf("Empty list");
}
// If the list is not empty
// If the head node contain required val
if(headNode->val == val) {
// If there is more than one node
if(headNode->link != headNode) {
// Make the head node as
current
curr = headNode;
// Parse thrrough the list until we
get the previous node of head node
while(curr->link!=headNode) {
curr = curr->link;
}
// Update the curr node link to
next node after head
curr->link = headNode->link;
// Update head node
headNode = headNode->link;
}
// If there is only one node
else
{
// Make head node null
headNode = NULL;
}
}
// If the head node does not contain required val and there is only
one node
else if(headNode->val != val && headNode->link ==
headNode) {
printf("Data not found");
}
// Otherwise make the head node as curr node
curr = headNode;
// Parse through the list until head node or required
node found
while(curr->link != headNode && curr->val != val)
{
// Prev node denote the previous node of curr
node
prev = curr;
curr = curr->link;
}
// Check the curr node has required val
if(curr->val == val) {
// Update the prev node link
prev->link = prev->link->link;
// free the curr node
free(curr);
}
// Otherwise val not found
else
printf("Data not found");
}