- 论坛徽章:
- 5
|
本帖最后由 seanking1987 于 2015-05-19 09:56 编辑
结贴~把list.h的cat和dog的NODE* 改为NODE就可以了
list.h- #ifndef __LIST_H_
- #define __LIST_H_
- typedef struct node {
- struct node* prev;
- struct node* next;
- }NODE;
- typedef struct cat {
- NODE node;
- int age;
- char name[20];
- }CAT;
- typedef struct dog {
- NODE node;
- int age;
- char name[20];
- int height;
- }DOG;
- typedef struct list {
- NODE node;
- int data;
- }LIST;
- #endif //__LIST_H_
复制代码 list.c- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include "list.h"
- void lstinit(LIST *list)
- {
- list->data = 0;
- list->node.prev = NULL;
- list->node.next = NULL;
- }
- void listadd(LIST *list,NODE* pnode)
- {
- //CAT *cat = (CAT *)pnode;
- //printf("%p--%s:%d\n",cat,cat->name,cat->age);
- NODE* tail = list->node.prev;
- pnode->prev = tail;
- pnode->next = NULL;
- if (tail)
- tail->next = pnode;
- else
- list->node.next = pnode;
- list->node.prev = pnode;
- //printf("%p--%s:%d\n",cat,cat->name,cat->age);
- //printf("%p--%s:%d\n",list->node.next,((CAT *)list->node.next)->name,((DOG *)list->node.next)->age);
- }
- void findage(LIST *list,int age)
- {
- NODE *node = list->node.next;
- //printf("%p\n",list->node.next);
- while (node)
- {
- CAT *cat = (CAT *)node;
- //printf("%p:%d %s\n",cat,cat->age,cat->name);
- if (cat->age == age)
- {
- printf("the %d age animal is cat:%s\n",cat->age,cat->name);
- return;
- }
- DOG *dog = (DOG *)node;
- if (dog->age == age)
- {
- printf("the %d age animal is cat:%s\n",dog->age,dog->name);
- return;
- }
- node = node->next;
- }
- printf("no %d age animal\n",age);
- }
- int main(int argc,char *argv[])
- {
- CAT* cat = (CAT *)malloc(sizeof(CAT));
- DOG* dog = (DOG *)malloc(sizeof(DOG));
- LIST* list = (LIST *)malloc(sizeof(LIST));
- cat->age = 2;
- strcpy(cat->name,"maomi");
- dog->age = 3;
- strcpy(dog->name,"dahuang");
- dog->height = 80;
- lstinit(list);
- //printf("%s:%d,%s:%d\n",cat->name,cat->age,dog->name,dog->age);
- listadd(list,(NODE *)cat);
- listadd(list,(NODE *)dog);
- //printf("%s:%d,%s:%d\n",cat->name,cat->age,dog->name,dog->age);
- //printf("%p,%p,%p,%p\n",cat,list->node.next,dog,list->node.next->next);
- findage(list,2);
- findage(list,3);
- findage(list,4);
- free(cat);
- free(dog);
- free(list);
- return 0;
- }
复制代码 运行结果:
the 2 age animal is cat:maomi
the 3 age animal is cat:dahuang
no 4 age animal |
|