本文共 2850 字,大约阅读时间需要 9 分钟。
Animal.h
#include#include /*“动物”类声明*/struct Animal{ /*成员属性*/ char name[128]; int age; int sex; int others; /*成员方法*/ void (*eat)(); void (*beat)(); void(*character)(); void (*test)(); struct Animal *next;};/*头插法建立链表函数声明*/struct Animal* putHeadDogLink(struct Animal* head);struct Animal* putHeadCatLink(struct Animal* head);struct Animal* putHeadHumanLink(struct Animal* head);/*根据名字检索对象函数声明*/struct Animal * findObjectName(char *name,struct Animal *head);/*“吃”函数声明*/void catEat();void dogEat();void humanEat();
Dog.c
#include"Animal.h"/*“狗”对象赋值*/struct Animal dog={ .name="lala", .age=5, .eat=dogEat};/*狗的eat函数*/void dogEat(){ printf("eat baba\n"); }/*头插法建立链表函数,若链表原来为空链表,则将dog作为链首*/struct Animal* putHeadDogLink(struct Animal* head){ if(head==NULL){ head=&dog; return head; }else{ dog.next=head; head=&dog; return head; } }
Cat.c
#include"Animal.h"/*“猫”对象赋值*/struct Animal cat={ .name="hihi", .age=2, .eat=catEat};/*猫的eat函数*/void catEat(){ printf("eat milk\n");}/*头插法建立链表函数,若链表原来为空链表,则将cat作为链首*/struct Animal* putHeadCatLink(struct Animal* head){ if(head==NULL){ head=&cat; return head; }else{ cat.next=head; head=&cat; return head; } }
Human.c
#include"Animal.h"/*“人”对象赋值*/struct Animal human={ .name="bobo", .age=18, .eat=humanEat};/*人的eat函数*/void humanEat(){ printf("eat rice\n");}/*头插法建立链表函数,若链表原来为空链表,则将human作为链首*/struct Animal* putHeadHumanLink(struct Animal* head){ if(head==NULL){ head=&human; return head; }else{ human.next=head; head=&human; return head; } }
Function.c
#include"Animal.h"/*根据名字检索对象函数,查找成功返回值为查到对象的地址,查找失败,返回NULL*/struct Animal * findObjectName(char *name,struct Animal *head){ struct Animal *tmp=head; /*判断链表是否为空链表*/ if(head==NULL){ printf("The list is empty\n"); return NULL; }else{ while(tmp!=NULL){ if(strcmp(tmp->name,name)==0){ return tmp; } tmp=tmp->next; } printf("no find name\n"); return NULL; }}
Main.c
#include "Animal.h"int main(){ char buf[128]={ '\0'}; struct Animal* head=NULL; struct Animal* tmp=NULL; /*头插法建立链表,将dog、cat、human三个对象组成链表*/ head=putHeadDogLink(head); head=putHeadCatLink(head); head=putHeadHumanLink(head); while(1){ /*清空buf*/ memset(buf,'\0',sizeof(buf)); printf("input name:\n"); scanf("%s",buf); /*根据名字检索对象函数,查找成功返回值为查到对象的地址,查找失败,返回NULL*/ tmp=findObjectName(buf,head); /*查找成功,将对象的姓名、年龄输出,同时执行对象的eat函数*/ if(tmp!=NULL){ tmp->eat(); printf("%s age:%d\n",tmp->name,tmp->age); } } return 0;}
gcc *.c
转载地址:http://qtxo.baihongyu.com/