我正在尝试根据节点数量n
将元素插入我的双向链表。比如,如果n
是4
,则输入的元素数量为:34 45 32 1
,但出现了segmentation fault
。有人可以告诉我问题出在哪里吗?
#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");
}
}
}
start= malloc()
就是一个可行的方法。 - this