链表删除算法

时间:2014-04-23 09:17:09

标签: list linked-list

此程序用于从链接列表中删除节点。它工作正常,但事实是它打印0而不是NOT打印已删除节点的值。 对于前者如果我的列表是1 - > 2 - > 3 - > -999.我想删除说2.然后最终列表打印为1 - > 0 - > - &gt ; 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);
}

1 个答案:

答案 0 :(得分:0)

在删除例程中重新排列指针时出错。 而不是

...
else {
    prev_ptr = curr_ptr->next;
}
...

你应该

...    
else {
    prev_ptr->next = curr_ptr->next;
}
...

显示0是因为你释放了curr_ptr(因此它指向无处)。但真正的问题是你不应该在列表中有它。