How can I go about removing a node from a linked list?
Here is my code:
void RemoveNode(Node * node, Node ** head) {
if (strcmp(node->state, (*(*head)->next).state) == 0) {
Node * temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node * current = (*head)->next;
Node * previous = *head;
while (current != NULL && previous != NULL) {
if (strcmp(node->state, (*current->next).state) == 0) {
Node * temp = current;
previous->next = current->next;
free(temp);
return;
}
current = current->next;
previous = previous->next;
}
return;
}
But I keep getting seg faults.
I feel like I'm doing something stupid.... Any ideas?
My guess:
void RemoveNode(Node * node, Node ** head) {
if (strcmp(node->state, ((*head)->state) == 0) {
Node * temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node * current = (*head)->next;
Node * previous = *head;
while (current != NULL && previous != NULL) {
if (strcmp(node->state, current->state) == 0) {
Node * temp = current;
previous->next = current->next;
free(temp);
return;
}
previous = current;
current = current->next;
}
return;
}