数据结构作业day4
1、头插法创建双向链表,节点是学生信息(学号,分数,姓名)
2、调用函数遍历链表所有信息
3、调用函数,求出分数是完数的学生,并输出该学生所有信息
4、调用函数,按照姓名查找某个学生是否存在,存在输出该学生是第几个节点。
dlink.h
#ifndef _DLINK_H_
#define _DLINK_H_
#include <myhead.h>
typedef struct students
{int id;float score;char name[20];
}stu;typedef struct node
{union{stu data;int len;};struct node *pro;struct node *next;
}Dlink,*Pdlink;Pdlink apply();
Pdlink create();void front_insert(Pdlink);
void input_dlink(Pdlink);void output_dlink(Pdlink);void prefect_num(Pdlink);void serch_name(Pdlink);
#endif
dlink.c
#include "dlink.h"Pdlink apply()
{Pdlink p = malloc(sizeof(Dlink));if(p == NULL){printf("申请失败!\n");return NULL;}return p;
}Pdlink create()
{Pdlink p = apply();if(p == NULL){printf("创建失败\n");}p->len =0;p->pro = NULL;p->next = NULL;return p;
}void front_insert(Pdlink L)
{Pdlink p = apply();stu e;scanf("%d%f%s",&e.id,&e.score,e.name);if(L->next == NULL){p->data = e;p->next =NULL;p->pro = L;L->next = p;}else{p->data = e;p->next = L->next;p->pro = L;L->next->pro = p;L->next = p;L->len++;}
}void input_dlink(Pdlink L)
{int i,n;printf("请输入学生数量:");scanf("%d",&n);for(i=0;i<n;i++){printf("请输入第%d位同学的信息:",i+1);front_insert(L);}}void output_dlink(Pdlink L)
{int i;Pdlink t = L->next;while(t!=NULL){printf("\t%d\t%.2f\t%s",t->data.id,t->data.score,t->data.name);t = t->next;printf("\n");}printf("\n");
}void prefect_num(Pdlink L)
{Pdlink t = L;int i,j,sum;for(i=0;i<L->len;i++){sum = 0;t = t->next;for(j=1;j<t->data.score;j++){if((int)t->data.score % j == 0){sum += j;}}if(sum==t->data.score){printf("学号:%d,分数:%.2f,姓名:%s",t->data.id,t->data.score,t->data.name);}}}void serch_name(Pdlink L)
{char s[20];int sub = -1,i;Pdlink t = L;printf("请输入需要查找的名字:");scanf("%s",s);for(i=0;i<L->len;i++){t = t->next;if(strcmp(t->data.name,s)==0){sub = i;}}if(sub == -1){printf("查找失败\n");}else{printf("这名学生在第%d个节点",sub+1);}
}
main.c
#include "dlink.h"
int main(int argc, const char *argv[])
{Pdlink L = create();//头插法创建链表input_dlink(L);output_dlink(L);//完美数查找prefect_num(L);//按名字查找,输出节点信息serch_name(L);return 0;
}
xmind