您好,欢迎访问三七文档
第10章指针与链表1分析在各种信息管理系统的程序设计中,常常需要存储大量的数据记录。如果使用结构体数组会带来哪些问题?2解决办法:采用动态存储分配的数据结构——链表10.1存储空间的分配与释放C语言标准函数库stdlib.h中提供了四个函数,用于实现内存的动态分配和释放。分别为:malloc(),calloc(),realloc()和free().1.malloc函数void*malloc(unsignedintsize);作用是:在内存的动态存储区申请一个长度为size的连续空间,并返回存储空间的起始地址;如果没有足够的内存空间可分配,则返回空指针NULL.3用法:由于函数返回类型为void,因此如果要将函数返回的指针赋给其它类型的指针变量,应当进行强制类型转换。例如:int*p=(int*)malloc(sizeof(int));structstud*p=(structstud*)malloc(sizeof(structstud));42.calloc函数void*calloc(unsignedn,unsignedsize);作用是:在内存的动态区分配n个长度为size的连续空间,并返回该存储空间的起始地址。主要用于为动态数组申请存储空间。例如:Int*p=(int*)calloc(10,sizeof(int));53.free函数voidfree(void*p);作用是:释放指针变量p指向的存储空间.注意:p只能是程序中此前最后一次调用malloc或calloc函数所返回的地址。例如:int*p,*q=(int*)calloc(10,sizeof(int));p=q;q++;free(p);610.2链式存储结构——链表链表可以动态的进行存储分配,每一个元素称为一个“结点”,每个结点都包括两部分:1249head1249A13561356B14751475C10211021DNULLhead:头指针,存放一个地址,指向链表中的第一个结点.1.数据域:存储用户需要的实际数据;2.指针域:指向下一个结点的地址.表尾:它的地址部分放一个“NULL”,链表到此结束.710.3单链表每个结点只含有一个指针,所有结点单向联系,每个结点的指针都指向下一个结点,形成一条线性链。带头结点的单向链表:在单向链表的第一个结点前虚加一个“头结点”,头指针head指向头结点,头结点的指针域指向第一个结点,头结点的数据域不使用。8可用结构体类型的变量来存储链表中的结点元素.1249head1249A13561356B14751475C10211021DNULL每一个结点中存放地址的部分可用指针来实现.例:structstudent{intnum;floatscore;structstudent*next;}1、建立和输出链表9简单静态链表#defineNULL0structstudent{longnum;floatscore;structstudent*next;};main(){structstudenta,b,c,*head,*p;a.num=9901;a.score=89.5;b.num=9903;b.score=90;c.num=9905;c.score=85;head=&a;a.next=&b;b.next=&c;c.next=NULL;p=head;do{printf(“%ld%5.2f\n”,p-num,p-score);p=p-next;}while(p!=NULL);}anumscorenextbcheadp990189.5990390990585&a&b&cNULL&a&b&cNULL10建立动态链表#defineNULL0#defineLENsizeof(structstudent)structstudent{longnum;floatscore;structstudent*next;};intn;动态建立链表structstudent*creat(void){structstudent*head,*pEnd,*pNew;n=0;pEnd=pNew=(structstudent*)malloc(LEN);scanf(“%ld,%f”,&pNew-num,&pNew-score);head=NULL;while(pNew-num!=0){n=n+1;if(n==1)head=pNew;elsepEnd-next=pNew;pEnd=pNew;pNew=(structstudent*)malloc(LEN);scanf(“%ld,%f”,&pNew-num,&pNew-score);}pEnd-next=NULL;return(head);}11链表的插入操作3、单链表的插入structstudent*insert(structstudent*head,structstudent*stud){structstudent*p1,*p2;p1=head;if(head==NULL){head=stud;stud-next=NULL;}else{while(p1-numstud-num&&p1-next!=NULL)){p2=p1;p1=p1-next;}if(p1-next!=NULL){if(head==p1)head=stud;elsep2-next=stud;stud-next=p1;}else{p1-next=stud;stud-next=NULL;}}n=n+1;return(head);}12链表的删除操作4、单链表的删除structstudent*del(structstudent*head,longnum){structstudent*p1,*p2;if(head==NULL){printf(“\nlistnull!\n”);exit(0);}p1=head;while(num!=p1-num&&p1-next!=NULL){p2=p1;p1=p1-next;}if(num==p1-num){if(p1==head)head=p1-next;elsep2-next=p1-next;printf(“delete:%ld\n”,num);n=n-1;}elseprintf(“%ldnotbeenfound!\n”,num);return(head);}13作业:P23710.1,10.214
本文标题:指针与链表
链接地址:https://www.777doc.com/doc-5339709 .html