I've read alot of the provided linked list segmentation faults on this site and attempted fixes like checking nullptrs before each use but I still can't get this to work. This is the link to the program on replit.
The program gives the intended result on test cases (using both input and command) 21 & 22 but gives segmentation faults on 23. Through method of elimination, I believe it is both the addNode & deleteByPhrase functions. The addNode function is supposed to insert a node at a given position within the linked list, and the deleteByPhrase function is supposed to delete any node whose phrase string contains the deletionPhrase.
void addNode(node* &h, int pos, string phrase)
{
if(pos == 0)
{
h = new node;
h->phrase = phrase;
h->id = pos;
nodeCount++;
h->next = nullptr;
}
else if(pos <= nodeCount)
{
node* y;
node* g;
g = h;
int count = 0;
while(count != pos && g!=nullptr)
{
y = g;
g = g->next;
count++;
}
node *n;
n = new node;
n->id = pos;
nodeCount++;
n->phrase = phrase;
n->next = g;
y->next = n;
}
}
void deleteByPhrase(node* &h, string deletionPhrase)
{
struct node* current = h;
struct node* previous = nullptr;
while(current != nullptr)
{
if(current->phrase.find(deletionPhrase) != string::npos)
{
if(current == h) {
h = h->next;
}else{
previous->next = nullptr;}
nodeCount--;
}
//store reference to current link
previous = current;
current = current->next;
}
}