1. 程式人生 > >帶頭節點單鏈表的建立 (C語言完整版)

帶頭節點單鏈表的建立 (C語言完整版)

#include <stdio.h>
#include <malloc.h>
#define N 5
typedef struct node
{
char name[20];
float score;
struct node *next;
}stud;


stud *creat(int n)
{
stud *p, *h, *s;
int i;
if((h=(stud*)malloc(sizeof(stud)))==NULL)
{
printf("No memory space can be allocated!");
exit(0);
}
h->name[0]='\0';
h->score=0;
h->next=NULL;
p=h;
for(i=0;i<n;i++)
{
if((s=(stud*)malloc(sizeof(stud)))==NULL)
{
printf("No memory space can be allocated!");
exit(0);
}
p->next=s;
printf("Enter the %d name and score",i+1);
scanf("%s%f",s->name,&s->score);
s->next=NULL;
p=s;
}
return(h);
}


void print(stud *h)//輸出連結串列
{
int n;
stud *p;
printf("\n Now, These %d records are:\n",N);
p=h->next ; //如果選擇p=h,則頭結點中的資料域中會出現亂碼
if(h !=NULL)
do
{
printf("%s%f\n",p->name,p->score);
p=p->next;
}while(p!=NULL);
}






main()
{
int number;
stud *head;
number=N;
head=creat(number);
print(head);
}

轉自——http://www.360doc.com/content/12/1214/13/8363527_253983319.shtml

本人稍做修改

? 頭結點的資料域 如果是三個 或更多 出現亂碼 怎麼處理

答只要讓 輸出函式中的p=h 改為 p=h->next;  就可以了!