1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 typedef struct student 5 { 6 int num; 7 float socre; 8 struct student *next; 9 }Student; 10 11 Student *creatlist(void) //创建空链表 12 { 13 Student *head=(Student *)malloc(sizeof(Student)); 14 head->next=NULL; 15 16 return head;//返回结构体头指针地址 17 } 18 19 void insertlist(Student *head,int num,float socre) //插入数据 20 { 21 Student *cur=(Student *)malloc(sizeof(Student));//给新节点申请空间 22 23 // while(num)不进行检查了因为输入的数据都是有效的 24 //cur=(Student *)malloc(sizeof(Student));上面已经申请了空间 25 26 cur->num=num; 27 cur->socre=socre;//给节点赋值 28 29 cur->next=head->next;//先把NULL那到新节点中 30 head->next=cur;//指向头结点的下一个节点 31 32 } 33 34 void print(Student *head)//遍历链表 35 { 36 head=head->next;//指向第一个有数据的节点 37 while(head)//最后一个节点的head->next为NULL 38 { 39 40 printf("num:%d,socre:%.f\n",head->num,head->socre); 41 head=head->next;//指向下一个节点 42 } 43 } 44 int main() 45 { 46 Student *head=creatlist();//得到空节点head的地址 47 int i=0; 48 float j=100; 49 for(i;i<10;i++,j--)//for循环插入数据 50 { 51 insertlist(head,i,j); 52 } 53 print(head); 54 system("pause"); 55 }
利用头插法——创建、插入、遍历链表
猜你喜欢
转载自www.cnblogs.com/huxiaobai/p/10199897.html
今日推荐
周排行