TA的每日心情 | 开心 2014-6-18 08:29 |
---|
签到天数: 14 天 [LV.3]偶尔看看II
滴水大师
 
- 积分
- 2345
|
题目
解决代码及点评
- <pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"></pre><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code">/************************************************************************/
- /*
- 10. 建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,
- 如果链表中的结点所包含的年龄等于此年龄,将此结点删除,输出最后的链表。
-
- */
- /************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <string.h>
-
- typedef struct student STU;
- struct student // 保存学生信息的节点结构体
- {
- int num;
- char name[10];
- int age;
- int sex;
- struct student * next;
- };
- STU * Init10() // 初始化链表
- {
- STU * p=(STU *)malloc(sizeof(STU)); // 初始化链表时,创建了一个头节点,该节点信息无意义
- if (p==NULL) // 如果内存申请失败,则
- {
- return NULL;
- }
- else
- p->next=NULL;
- return p; // 返回创建的头结点
- }
- void Insert10(STU * head,int num,int aeg,int sex,char * name) // 将新学生信息插入链表
- { STU * last=head;
- if (last==NULL)
- {
- return;
- }
- while(last->next!=NULL) // 找到最后一个节点
- last=last->next;
- STU *p=(STU *)malloc(sizeof(STU)); // 申请新节点空间
- if (p==NULL)
- {
- return;
- }
- else
- {
- p->num=num; // 初始化新节点
- strcpy_s(p->name,name);
- p->age=aeg;
- p->sex=sex;
- last->next=p; // 把新节点保存在链表最后
- p->next=NULL;
-
- }
- }
- void DeleteNode10(STU* pre,STU *cur)
- {
- pre->next=cur->next; // 删除cur节点,pre是cur的前置节点
- free(cur);
- }
- void printfNodes10(STU *head) // 该函数遍历所有node,进行打印输出
- {
- STU *p=head->next;
- while(p!=NULL)
- {
- printf("%5d",p->age);
- p=p->next;
- }
- printf("\n");
- }
- void main()
- { int num;
- scanf_s("%d",&num); // 输入
- STU * A=Init10(); // 初始化链表,并插入一堆数据
- Insert10(A,1,12,1,"abc");
- Insert10(A,2,13,0,"abc");
- Insert10(A,3,14,1,"abc");
- Insert10(A,3,14,0,"abc");
- Insert10(A,4,15,1,"abc");
- printfNodes10(A);
- STU * index=A->next;
- STU * flower=A;
- while(index!=NULL) // 遍历所有节点
- {
- if (index->age==num) // 如果节点的年纪是指定需要删除的年纪
- {
- DeleteNode10(flower,index); // 删除该节点
- index=flower->next; // 继续遍历
- }
- else
- {
- index=index->next; // 只是继续遍历
- flower=flower->next;
- }
-
-
- }
- printfNodes10(A); // 输出新的链表
- system("pause");
- }</pre><br><br></pre></pre>
|
|