Reputation:
Do you understand why when i call the delete
function here the output become an infinite loop? Without that function the code works.
int main(){
node *head = NULL;
end(&head);
begin(&head);
begin(&head);
end(&head);
begin(&head);
end(&head);
begin(&head);
delete(&head);
display(head);
return 0;
}
void delete(node **head){
node *tmp,*prev = NULL;
int num;
printf("Insert the number that you want to delete: ");
scanf("%d",&num);
tmp = *head;
if (tmp->data == num){
*head = tmp->next;
free(tmp);
return;
}
while(tmp->data!=num && tmp!=NULL){
prev = tmp;
tmp = tmp->next;
}
if(tmp == NULL){
return;
}
prev->next = tmp->next;
free(tmp);
}
Those are my other function:
void begin(node **head){
node *new;
int num;
new = malloc(sizeof(node));
if(new == NULL){
perror("malloc");
EXIT_FAILURE;
}
printf("Insert number at the beginning: ");
scanf("%d",&num);
new->data = num;
new->next = *head;
*head = new;
}
void end(node **head){
int num;
node *tmp,*new;
new = malloc(sizeof(node));
if(new == NULL){
perror("malloc");
EXIT_FAILURE;
}
printf("Insert number at the end: ");
scanf("%d",&num);
new->data = num;
tmp = *head;
if(tmp == NULL){
tmp = malloc(sizeof(node));
tmp->data = num;
tmp->next = NULL;
}
while(tmp->next!=NULL){
tmp = tmp->next;
}
new->next = NULL;
tmp->next = new;
}
void display(node *head){
node *tmp;
if(head == NULL){
printf("Empty list");
}
else{
while(tmp!=NULL){
printf("%d ",tmp->data);
tmp = tmp->next;
}
}
}
Upvotes: 1
Views: 74
Reputation:
Ok i understand the problem. I forgot to add tmp = head
in the else{}
condition in the display()
function
Upvotes: 1
Reputation: 31
temp != NULL condition should be ahead of temp->data != num inside while loop. Because if the temp reaches to the end of list without any match then temp will be NULL and you can't have check value(temp->data != num) for NULL pointer.
Upvotes: 1