建立單鏈表(字串型)並輸出
阿新 • • 發佈:2019-02-12
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define N 3
typedef struct node
{
char name[20];
struct node *link;
}stud;
stud *creat(int n)
{
stud *p,*h,*s;
int i;
if((h=(stud*)malloc(sizeof(stud)))==NULL)
{
printf("不能分配記憶體空間!");
exit (0);
}
h->name[0] = '\0';
h->link=NULL;
p = h;
for(i = 0;i<n;i++)
{
if((s=(stud*)malloc(sizeof(stud)))==NULL)
{
printf("不能分配記憶體空間!");
exit(0);
}
p->link = s;
printf("請輸入第%d個人的名字",i+1);
scanf("%s",s->name);
s->link = NULL;
p = s;
}
return (h);
}
void printList(stud *p)
{
while(p->link)
{
p = p->link;
printf("%s\n",p->name);
}
}
void main()
{
int number;
stud *head;
number = N;
head = creat(number);
printList(head);
}