我的输入程序,在双链表中,终止,错误代码为-1073741819(0xC0000005)

问题描述 投票:0回答:1

这是我在双向链接列表中输入数据的功能

void input(int element){
struct node *p=head,*q=(struct node *)malloc(sizeof(struct node));
if(p==NULL){
    head=q;
    q->data=element;
    q->prev=NULL;
    q->next=NULL;
}
else{
    while(p->next!=NULL){
        p=p->next;
    }
    p->next=q;
    q->prev=p;
    q->next=NULL;
    q->data=element;
}}

这是我的功能,用于在双链表中显示数据

void display(){
struct node *p=head;
while(p!=NULL){
    p=p->next;
    printf("%d   ",p->data);
}
printf("\n");}

如果我在我的双向链接列表中输入了一个或多个数据并尝试显示我的链接列表,则程序终止,错误代码为-1073741819(0xC0000005)

如果我在链接列表中输入1,2,3,4输出是:

2 3 4进程结束,退出代码为-1073741819(0xC0000005)

这是我程序的完整代码:

struct node {
int data;
struct node *next;
struct node *prev;
}*head=NULL;
void display(){
struct node *p=head;
while(p!=NULL){
    p=p->next;
    printf("%d   ",p->data);
}
printf("\n");
}
void input(int element){
struct node *p=head,*q=(struct node *)malloc(sizeof(struct node));
if(p==NULL){
    head=q;
    q->data=element;
    q->prev=NULL;
    q->next=NULL;
}
else{
    while(p->next!=NULL){
        p=p->next;
    }
    p->next=q;
    q->prev=p;
    q->next=NULL;
    q->data=element;
}
}
int main() {
int x;
while(1){
    printf("Press   1.INSERT   4.DISPLAY ALL ELEMENTS   5.QUIT   \n");
    scanf("%d",&x);
    if(x==1){
        int element;
        printf("\n write your element");
        scanf("%d",&element);
        input(element);
    }

    else if(x==4){
        display();
    }
    else if (x==5){
        return 0;
    }

}
}
c linked-list doubly-linked-list
1个回答
1
投票

由于两个语句的无效顺序,所以函数显示中存在错误。

代替

void display(){
struct node *p=head;
while(p!=NULL){
    p=p->next;
    printf("%d   ",p->data);
}
printf("\n");}

至少应该看起来像

void display(){
struct node *p=head;
while(p!=NULL){
    printf("%d   ",p->data);
    p=p->next;
}
printf("\n");}
© www.soinside.com 2019 - 2024. All rights reserved.