0
该程序用于从链接列表中删除节点。它工作正常,但问题是它打印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 entrying\n");
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);
}
谢谢ondrej – tofu