C语言程序设计课件-第8章 结构体(二)-- 结构体的应用.ppt
8.3.3单链表--建立动态链表建立动态链表是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点,并输入各结点数据,并建立起前后相链的关系。8.3.3单链表--建立动态链表【例1】写一函数建立一个有多名学生数据的单向动态链表。学生数据从键盘输入,当输入学号为999时,输入结束。解题思路:定义3个指针变量:head,p1和rear,它们都是用来指向structStudent类型数据,其中head为单链表的头指针,p1指向当前结点,rear指向当前链表的尾结点。structStudent*head,*p1,*rear;解题思路:初始状态下,链表为空:head=NULL;rear=NULL;用malloc函数开辟一个结点,并使p1指向它。p1p1=(structStudent*)malloc(LEN);解题思路:读入一个学生的数据给p1所指的结点p1scanf(%ld,%f,p1-num,p1-score);10188.5解题思路:如果是第一个结点(head==NULL),那么当前结点既是单链表的头结点,也是尾结点:head=p1;rear=p1;headp110188.5rear解题思路:开辟一个新结点并使p1指向它p1=(structStudent*)malloc(LEN);headp110188.5rear解题思路:接着输入该结点的数据headp1scanf(%ld,%f,p1-num,p1-score);10188.510390rear解题思路:链接尾结点(rear)和当前结点(p1)headp1rear-next=p1;10188.510390rear解题思路:使rear指向新的尾结点rear=p1;headp110188.510390rear解题思路:循环重复刚才的过程。如果某一个结点的学号输入为999,循环结束。最后一个结点的next域置为NULL:rear-next=NULLhead10188.510390NULLp1rear#includestdio.h#includestdlib.h#defineLENsizeof(structStudent)structStudent{longnum;floatscore;structStudent*next;};structStudent类型数据的长度structStudent*creat()//函数返回单链表的头指针{structStudent*head=NULL,*p1,*rear=NULL;p1=(structStudent*)malloc(LEN);scanf(“%ld,%f”,p1-num,p1-score);p1总是开辟新结点rear总是指向最后结点Head总是指向头结点structStudent*creat(){structStudent*head=NULL,*p1,*rear=NULL;p1=(structStudent*)malloc(LEN);scanf(“%ld,%f”,p1-num,p1-score);{if(head==NULL)head=p1; elserear-next=p1; rear=p1;//rear永远指向链表尾结点 p1=(structStudent*)malloc(LEN); scanf(“%ld,%f”,p1-num,p1-score); }structStudent*creat(){structStudent*head=NULL,*p1,*rear=NULL;p1=(structStudent*)malloc(LEN);scanf(“%ld,%f”,p1-num,p1-score);while(p1-num!=999){if(head==NULL)head=p1; elserear-next=p1; rear=p1; p1=(structStudent*)malloc(LEN); scanf(“%ld,%f”,p1-num,p1-score); }structStudent*cre