文档详情

C++第六章-结构和链表.ppt

发布:2017-11-24约8.78千字共43页下载文档
文本预览下载声明
第六章 结构和链表 6.1 结构类型 6.2 结构在链表中的应用 6.3 应用程序 初始化 : struct person { char name[15]; char sex; int age; } p1 = {FangMin, F, 24}; struct person { char name[15]; char sex; int age; } p[10] = {{FangMin, F, 24},{LiLin, M, 23}}; 【例6.2】 已知有关于学生的结构类型说明,同时定义并初始化了该类型的结构数组,计算该组学生的平均成绩并统计不及格人数。假设学生的信息中包含学号、姓名、性别和成绩。 程序: #include iostream.h struct stu { int num; char *name; char sex; float score; }student[5]={{101,Li ping,M,45}, {102,Zhang ping,M,62.5}, {103,He fang,F,92.5}, {104,Cheng ling,F,87}, {105,Wang ming,M,58} }; float ave(struct stu *ps) //指向结构的指针做形式参数 { int i; float s=0; for(i=0;i5;i++,ps++) s+=ps-score; //利用指针访问结构变量的成员 return(s/5); } int nopass(struct stu *ps) { int c=0,i; for(i=0;i5;i++,ps++) if(ps-score60) c++; return c; } 6.2 结构的应用——链表 6.2.2 链表的建立 6.2.3 单链表的基本操作 2、 统计结点个数 4、在链表中插入结点 5、删除链表中的某个结点 假定有一个指针behind 指向链表中的某个结点,newnode指向待插入结点。 newnode 12 10 15 19 behind front 如果有一个指针front指向behind的前驱,则仅需编写下面的两个语句,即可实现插入。 ; ; 如果没有behind指针,插入操作仍然可以完成。 newnode-next=front-next; front-next=newnode; 思考题:上述两个语句的次序能否交换?为什么? newnode-next=behind front-next=newnode behind 7 两种特殊情况: 1. 在表头结点之前插入: ; ; 2. 在尾结点之后插入: ; ; newnode head behind 6 7 newnode 8 【例6.7】编写函数,实现在头结点为head的链表中插入值为x的结点。 newnode-next=behind head=newnode behind-next=newnode NULL newnode-next=NULL struct node * insert(node *head,int x) { struct node *behind,*front,*newnode; newnode=new node; newnode-data=x; behind=head; if(head==NULL) //空表 { head=newnode; newnode-next=NULL; } else //非空表
显示全部
相似文档