C语言写的循环单链表 例子简单 便于阅读和复习

来源:互联网 发布:淘宝便携自行车 编辑:程序博客网 时间:2024/06/05 14:33
#include<stdio.h>
#include<stdlib.h>


typedef struct
{
char name[20];
struct node *next;
}staff;
/*创建单链表 n:需要向链表中添加的人数*/
staff *create(int n)
{
/* *h:指向头结点 *p:指向当前结点的前一个结点,*s:指向当前结点*/
staff *p,*h,*s;
int i;
if( (h = (staff *)malloc(sizeof(staff))) == NULL)
{
printf("ERROR!");
exit(0);
}
h -> name[0] = '\0';/*头节点数据域为空 指针域指向空*/
h -> next = NULL;


p = h;/*p指向表头结点*/
for(i = 0; i < n; i++)
{
if( (s = (staff *) malloc(sizeof(staff))) == NULL ) /*分配新存储空间并检测*/
        {
            printf("ERROR!");
            exit(0);
        }
p -> next = s;
printf("Please input the name of staff:\n");
//给新的节点的数据域赋值
scanf("%s",s -> name);
s -> next = NULL;
p = s;
}
//单链表:尾节点指针域指向NULL 环形链表:尾节点指针域指向头节点
p -> next = h;
return(h);
}


int main()
{
int num;
staff *head;
staff *p;
printf("Input the number of people:\n");
    scanf("%d",&num);
head = create(num);
p = head;
while(p -> next != NULL)
{
printf("%s\n",p -> name);
p = p -> next;
}
return 0;
}
原创粉丝点击