C语言创建单链表,输出单链表的内容。

来源:互联网 发布:电脑工作备忘录软件 编辑:程序博客网 时间:2024/06/05 00:36
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
#define NEW (struct node *)malloc(sizeof(struct node))
struct node{
char name[20],tel[9];
struct node *next;
};
struct node *create() //返回指针节点的地址
{
struct node *h,*p,*q; //头节点,第一个节点,第二节点
char name[20];  //姓名
h=NULL;  //初始h为空
printf("name: ");
gets(name);  //输入名字
while(strlen(name)!=0)  //当输入名字不为空则循环
{
p=NEW; //创建新的内存空间
if(p==NULL)  //如果创建失败
{
printf("Allocation failure\n");
exit(0);
}
strcpy(p->name,name);  //给结点赋值
printf("tel: ");  
gets(p->tel);  //输入电话号码
p->next=NULL;   //下一结点为空
if(h==NULL)  //如果h为空,则h=p
h=p;
else        //否则往下循环
q->next=p;  
q=p;
printf("name: ");
gets(name);
}
return(h);
}
void printlist(struct node *head)
{
struct node *p;
p=head;
while(p!=NULL)
{
printf("%s\t%s\t\n",p->name,p->tel);
p=p->next;
}
}
main()
{
struct node *head;
head=create();
printlist(head);
}
0 0
原创粉丝点击