我刚接触链表,现在在节点的生成上遇到了困难。
我可以生成链表的第一个节点,但是gets()
函数似乎不能暂停执行来填充下一个节点。
输出结果如下:
Var name : var
Do you want to continue ?y
Var name : Do you want to continue ? // Here I cannot input second data
这是我的代码:
struct data
{
char name[50];
struct data* next;
};
struct data* head=NULL;
struct data* current=NULL;
void CreateConfig()
{
head = malloc(sizeof(struct data));
head->next=NULL;
current = head;
char ch;
while(1)
{
printf("Var name : ");
gets(current->name); //Here is the problem,
printf("Do you want to continue ?");
ch=getchar();
if(ch=='n')
{
current->next=NULL;
break;
}
current->next= malloc(sizeof(struct data));
current=current->next;
}
}
malloc
前添加(data *)
,像这样:(data *) malloc(sizeof(struct data))
。 - behzad.nouri