输入 i am a student,输完一个单词按enter再输入,输‘0’结束,输出结果就乱了,为什么呢?
但是直接输入 i am a student就可以完整输出
#include<stdio.h>
#include<stdlib.h>
//定义结构体
struct list
{
char data[15];
struct list *next;
};
typedef struct list node;
typedef node *link;
//建立链表
link create_list (link head)
{
link pointer,newpointer;
char data1[15];
int i;
head=(link)malloc(sizeof(node));
if(head==NULL)
{
printf("error");
}
else
{
printf("input data:\n");
gets(data1);
for(i=0;i<15;i++)
head->data[i]=data1[i];
head->next=NULL;
}
while(1)
{
newpointer=(link)malloc(sizeof(node));
if(newpointer==NULL)
{
printf("error");
}
else
{
gets(data1);
if(data1[0]=='0')
break;
else
{
for(i=0;i<15;i++)
head->data[i]=data1[i];
newpointer->next=head;
head=newpointer;
}
}
}
return head;
}
//输出链表
void printf_list (link head)
{
link pointer;
pointer=head;
printf("data is:");
while(pointer!=NULL)
{
printf("%s",pointer->data);
pointer=pointer->next;
}
}
//释放链表
void free_list (link head)
{
link pointer;
while(head!=NULL)
{
pointer=head;
head=head->next;
free(pointer);
}
}
//主函数
int main()
{
link head;
head=(link)malloc(sizeof(node));
if(head==NULL)
printf("error");
else
{
head=create_list(head);
printf_list(head);
free_list(head);
}
return 0;
}