So I am new to data structures and I am trying out linked lists. I have made a class Node with an int key, int del and Node* next. When I try to delete nodes by giving delete function (Del) a key, it works perfectly for head node or any node existing in the list but when I give a key that doesn't exist in the list it returns with a segmentation fault.
void Node::Del(int k) // here k is the key given to search
{
Node *curr = head; // ptr that traverses the list
Node *temp = NULL; // the pointer trails behind curr to store value of node one position behind curr
while (curr->key != k && curr != NULL)
{
temp = curr;
curr = curr->next;
}
if (curr == NULL) // if key not found (not working properly)
{
return;
}
else if (curr == head) // if head contains the key
{
head = curr->next;
delete curr;
return;
}
else if (curr->key == k) // if key exists in the node
{
temp->next = curr->next;
delete curr;
}
}
int main()
{
Node n1;
n1.Insert(1, 1);
n1.Insert(2, 2);
n1.Insert(3, 3);
n1.Insert(4, 4);
n1.Insert(5, 5);
n1.Del(7);
n1.print();
}
Output:
1 1
2 2
3 3
4 4
5 5
zsh: segmentation fault
I have a condition after traversing that if( curr == NULL ){ return;} meaning it searched till the end and didn't find the key and exit the loop (as per my understanding) , but instead it It returns segmentation fault.
nextthenif (curr == NULL)will not evaluate totrue. Please post a minimal reproducible example - 463035818_is_not_a_number