鏈表與結構體的結合,可以很好的方便輸入輸出,以后使用鏈表時只需要將結構體的信息稍作修改就可以使用,非常方便!!! 下面是寫學生學號和姓名的結構體與鏈表的結合create函數! 1#include “stdio.h” 2 3typedef struct node{ 4 int number; 5 char name[20]; 6 }node; 7 8 typedef struct student{ 9 node information; 10 struct student *next; 11 }student; 12 13 int iCount; 14 15 struct student *create() 16 { 17 int i; 18 node information; 19 struct student *head; //頭指針 方便以后插入與刪除等一系列操作 20 struct student *end; //位置指針 21 struct student *new; //創建空間的新指針 22 new = end = (struct student *)malloc(sizeof(student)); 23 head = NULL; 24 if(new == NULL) //如果申請堆空間失敗 則結束進程返回-1 25 {
26 PRintf(“申請空間失敗/n”);
27 goto err; 28 } 29 printf(“請先輸入學號,再輸入姓名:/n”); 30 scanf(“%d”,&information.number); 31 scanf(“%s”,information.name); 32 new->information = information; //把結構體信息直接輸入到鏈表中,方便快捷 33 for(i=0;new->information.number>0;i++) 34 { 35 iCount++; 36 if(iCount == 1) 37 { 38 new -> next = NULL; 39 end = new; 40 head = end; 41 } 42 else 43 { 44 new -> next = NULL; 45 end = new; 46 new = new -> next; 47 } 48 new = (struct student*)malloc(sizeof(student)); 49 scanf(“%d”,&information.number); 50 scanf(“%s”,information.name); 51 new -> information = information; 52 }
53 return head; 54 err: 55 return -1; 56 } 57 58 int main() 59 { 60 student *A; 61 A = create(); 62 return 0; 63 }
新聞熱點
疑難解答