1. 程式人生 > >利用頭插法——建立、插入、遍歷連結串列

利用頭插法——建立、插入、遍歷連結串列

 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 }