关于C语言创建链表的问题

来源:百度知道 编辑:UC知道 时间:2024/06/04 16:46:43
下面是源代码,能解释下吗
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
struct node
{
char name[20];
char tel[9];
struct node *next;
};

struct node *create()
{
struct node *head;
struct node *p,*q;
char name[20];
head=NULL;
printf("name:");
gets(name);
while(strlen(name)!=0)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Allocation failure\n");
exit(0);

}
strcpy(p->name,name);
printf("tel:");
gets(p->tel);
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
printf("name:");
gets(name);
}
return head;
}

void main()
{
struct node *head;
head=create();
}

#include <iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
struct node //结构体
{
char name[20]; //姓名数组
char tel[9]; //电话数组
struct node *next; //下个节点指针
};

struct node *create()
{
struct node *head;//定义链表头指针
struct node *p,*q; //定义两个节点指针
char name[20]; //定义一个数组
head=NULL;
printf("name:"); //在DOS_LIKE屏幕里显示name:
gets(name); //在DOS_LIKE屏幕里输入name
while(strlen(name)!=0) //当name不为空时
{
p=(struct node *)malloc(sizeof(struct node));//用MALLOC为指针开辟一个内存空间,用于存放结构体
if(p==NULL) //如果P空
{
printf("Allocation failure\n");
exit(0);//退出

}
strcpy(p->name,name);//将输入的name拷贝到你创建内存结构体的name上去
printf("tel:");//在DOS_LIKE屏幕里显示tel:
gets(p->tel);//在DOS_LIKE屏幕里输入tel:
p->next=NULL;//将下个节点指针赋值为空
if(head==NULL)//he