此程序用于从链表中删除节点。它工作正常,但问题是它打印0,而不是不打印已删除节点的值。例如,如果我的列表是1->2->3->-999。我想删除,比如说2。然后,最终列表打印为1-->0-->3-->-999。为什么是0???
enter code here
#include<stdio.h>
#include<malloc.h>
struct list {
int number;
struct list *next;
};
typedef struct list node;
void create(node *);
void print(node *);
node *delete(node *,int);
main() {
int key;
node *head;
head = (node *)malloc(sizeof(node));
create(head);
printf("Your list as you entered is....................n");
print(head);
printf("Which element do you want to delete?n ");
scanf("%d",&key);
head = delete(head,key);
printf("The new list is ..............................n ");
print(head);
return 0;
}
void create(node *list) {
printf("Enter a number,-999 to stop data entryingn");
scanf("%d",&list->number);
if(list->number == -999) {
list->next = NULL;
}
else {
list->next = (node *)malloc(sizeof(node));
create(list->next);
}
}
void print(node *list) {
if(list->number != -999) {
printf("%d-->",list->number);
print(list->next); }
else {
printf("%d",list->number);
}
}
node *delete(node *list,int key) {
node *prev_ptr = NULL;
node *curr_ptr;
for(curr_ptr=list;curr_ptr!=NULL;prev_ptr=curr_ptr,curr_ptr=curr_ptr->next) {
if(curr_ptr->number == key) {
break;
}
}
if(prev_ptr == NULL) {
list = curr_ptr->next;
}
else {
prev_ptr = curr_ptr->next;
}
free(curr_ptr);
return(list);
}
在delete例程中重新排列指针时出错。代替
...
else {
prev_ptr = curr_ptr->next;
}
...
你应该有
...
else {
prev_ptr->next = curr_ptr->next;
}
...
显示0是因为您释放了curr_ptr(因此它指向任何位置)。但真正的问题是你不应该把它列入清单。