C语言单链表和结构体的结合

3/8/2017来源:ASP.NET技巧人气:1552

链表与结构体的结合,可以很好的方便输入输出,以后使用链表时只需要将结构体的信息稍作修改就可以使用,非常方便!!! 下面是写学生学号和姓名的结构体与链表的结合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 }