C中双链表中出现意外错误
发布时间:2020-12-16 09:47:26 所属栏目:百科 来源:网络整理
导读:我试图根据节点数n在我的双链表中插入元素.如果n为4,那么输入的元素数量为:34 45 32 1但是会出现分段错误.谁能告诉我哪里出错了? #includestdio.h#includemalloc.hstruct node{ struct node *prev; struct node *next; int info; }*start;create_list(int
我试图根据节点数n在我的双链表中插入元素.如果n为4,那么输入的元素数量为:34 45 32 1但是会出现分段错误.谁能告诉我哪里出错了?
#include<stdio.h> #include<malloc.h> struct node{ struct node *prev; struct node *next; int info; }*start; create_list(int num) { printf("Hi I entered!n"); struct node *q,*tmp; tmp= malloc(sizeof(struct node)); tmp->info=num; tmp->next=NULL; if(start==NULL) { printf("Hi I am null!n"); tmp->prev=NULL; start->prev=tmp; start=tmp; } else { printf("Hi I am no more null!n"); q=start; while(q->next!=NULL) q=q->next; q->next=tmp; tmp->prev=q; } } int main(){ int choice,n,elem,i; start = NULL; printf("Enter your choice of number: n"); scanf("%d",&choice); while(1) { switch(choice) { case 1: printf("Enter the number of nodes: n"); scanf("%d",&n); for(i=0; i<n; i++) { printf("Enter the elemnts: n"); scanf("%d",&elem); create_list(elem); } break; default: printf("You have tyoed wrong!n"); } } } 解决方法if(start==NULL) { ... start->prev=tmp; 如果start为NULL,则上面的赋值不正确. 我建议在分配新节点时将prev初始化为NULL,如下所示: tmp= malloc(sizeof(struct node)); tmp->info=num; tmp->next=NULL; tmp->prev=NULL; // add this if(start==NULL) { printf("Hi I am null!n"); start=tmp; } .... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |