链表C语言中使用数组时数组的长度由定义说明整个程序中.pptx
C语言中使用数组时,数组的长度由定义说明,整个程序中固定不变。C语言中不允许动态数组类型。但在实际应用中,所需的内存空间取决于实际输入的数据,而无法预先确定。显然用数组的办法很难解决。为了解决上述问题,C语言提供了一些内存管理函数,这些内存管理函数可以按需要动态地分配内存空间,也可把不再使用的空间回收待用。此时引入链表,本节将介绍链表的定义及其应用。;7.6.1链表的定义;例如,一个存放学生学号和成绩的结点应为以下结构:
structstu
{
intnum;
intscore;
structstu*next;
}
前两个成员项组成数据域,后一个成员项next构成指针域,它是一个指向stu类型结构的指针变量。
;7.6.2链表的常用操作;TYPE*creat(intn)
{
structstu*head,*pf,*pb;
inti;
for(i=0;in;i++)
{
pb=(TYPE*)malloc(LEN);
printf(inputNumberandAge\n);
scanf(%d%d,pb-num,pb-age);
if(i==0)
pf=head=pb;
elsepf-next=pb;
pb-next=NULL;
pf=pb;
}
return(head);
};【例7-17】链表的建立与内容输出。
#includestdio.h
structdate
{
intyear,month,day;
structdate*next;
};
intmain()
{
structdated1={2010,10,10,0};
structdated2={2010,12,31,0};
structdated3={2011,1,1,0};
structdate*p=d1;
d1.next=d2;d2.next=d3;d3.next=NULL;
while(p!=NULL)
{printf(%d/%d/%d\n,p-year,p-month,p-day);
p=p-next;}}