您的位置:首页 > 编程语言 > C语言/C++

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

2013-12-19 20:59 253 查看
#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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息