双链表的删除算法

时间:2018-05-30 07:06:51

标签: c doubly-linked-list

#include<stdio.h>
#include<malloc.h>

struct list {
    char name[30];
    char subject1[30];
    char subject2[30];
    struct list* next;
    struct list* previous;
};

typedef struct list node;

node input(node* n1)
{
    node n2;
    n2.previous=n1;
    n1->next=&n2;
    n2.next=NULL;
    scanf("%s",n2.name);
    scanf("%s",n2.subject1);
    scanf("%s",n2.subject2);
    return n2;
}

void delete(node *n1)
{
    if(n1->next!=NULL)  
        n1->previous->next=n1->next;
    else
        n1->previous->next=NULL;
    if(n1->previous!=NULL)  
        n1->next->previous=n1->previous;
    printf("\nDeleting....");
    free(n1);
}

int main()
{
    node* start;
    start=(node*)malloc(sizeof(node));
    node n1=input(start);
    node n2=input(&n1);
    start->previous=NULL;
    printf("%s %s %s %s %s %s",n1.name,n1.subject1,n1.subject2,n2.name,n2.subject1,n2.subject2);
    delete(&n1);
    delete(&n2);
    delete(start);
    return 0;
}

删除操作不正确。它给出了一个未处理的异常,返回255错误。此外,在书籍中只删除n1节点,并保持开始(标题)和最后一个节点不变。但是,我想删除所有节点和标头。请解释并纠正。另外,我用C和C ++编写这段代码。请相应更正。

0 个答案:

没有答案