您了解我为什么在这里调用delete
函数时输出变成无限循环的原因吗?没有该功能,代码将起作用。
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);
}
这些是我的其他功能:
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;
}
}
}
答案 0 :(得分:1)
temp!= NULL条件应在while循环内位于temp-> data!= num之前。 因为如果temp到达列表的末尾而没有任何匹配,则temp将为NULL,并且您将没有NULL指针的检查值(temp-> data!= num)。
答案 1 :(得分:1)
好的,我明白问题所在。我忘记在tmp = head
函数的else{}
条件下添加display()