- 1、本文档共58页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
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
文档评论(0)