I am creating a program in which you can and delete a node at any time. However, when I try to delete the last node in the list, the program crashes. Can somebody tell me what I am doing wrong?
void delete_node(Node **head_ref) {
int position, counter = 0;
Node *curr_node = *head_ref;
if(*head_ref == NULL) {
printf("No nodes to delete!");
return;
}
printf("Enter position between 1 and %d: ", node_number);
scanf("%d", &position);
if(position == 1) {
*head_ref = (*head_ref)->next;
free(curr_node);
} else if(position == node_number) {
while(counter != position) {
counter++;
if(counter == position - 1)
curr_node->next = NULL;
curr_node = curr_node->next;
}
}
printf("\nNode deleted successfully!\n");
if( *head_ref == NULL )
printf("\nLast node deleted!\n");
}
I am calling the function in main
:
int main() {
//... other part of the program
delete_node(&head);
}