Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2160455
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: C/C++

2012-03-17 09:51:24


点击(此处)折叠或打开

  1. list.h
  2. --------------------------------------
  3. #ifndef _LIST_H
  4. #define _LIST_H

  5. typedef struct _node
  6. {
  7.    void *data;
  8.    struct _node * next;
  9. }NODE;

  10. typedef struct
  11. {
  12.     NODE *head;
  13.     NODE *last;
  14.     int length;
  15. }LIST;

  16.  LIST *InitList();

  17.  int InsertList(LIST *l,void *data,int size);
  18.  NODE * FindNodeByKey(LIST *l,void *key,int (*compare)(void *,void *));
  19. #endif

点击(此处)折叠或打开

  1. list.c 链表的实现
  2. --------------------------------------
  3. NODE * FindNodeByKey(LIST *l,void *key,int (*compare)(void *,void *)) //函数指针
  4. {
  5.       NODE *p=NULL;
  6.      if(l==NULL||key==NULL||compare==NULL)
  7.          return NULL;
  8.      p=l->head;
  9.      while(p)
  10.      {
  11.          if(compare(p->data,key)==1)
  12.              return p;
  13.          p=p->next;
  14.      }
  15.      return NULL;
  16. }
为了通用性,我们将查找的一些条件condition信息放在应用层,给链表只是传递一个函数指针就OK.
主要是考虑到大型系统数据量大,链表中可能存放不同类型的数据。
链表实际上就是一个内存数据库,并且我们给赋予了一些操作。
 
应用层:client端

点击(此处)折叠或打开

  1. //为了通用性,比较就由应用层来决定
  2. int CompareByName(void *info,void *key) //仔细体会无类型参数的好处:为了通用性
  3. {
  4.      struct STU *stu=(struct STU *)info; //将传进来的数据域强制转换成我们的数据类型
  5.      char *name=(char *)key;
  6.      return strcmp(stu->name,name)==0 ? 1:0;
  7. }

  8. int CompareBySno(void *info,void *key)
  9. {
  10.      struct STU *stu=(struct STU *)info;
  11.      char *sno=(char *)key;
  12.      return strcmp(stu->sno,sno)==0 ? 1:0;
  13. }
main函数的调用:

点击(此处)折叠或打开

  1. void main()
  2. {
  3.     int i;
  4.     NODE *res=NULL; //定义临时的指针来存放返回的结果
  5.     char name[]="wang wu",sno[]="S101";
  6.     LIST *list=InitList();
  7.     for(i=0;i<3;i++)
  8.      InsertList(list,&s[i],sizeof(s[i]));
  9.     
  10.     
  11.      res=FindNodeByKey(list,name,CompareByName); //函数名称就代表了这个函数的首地址
  12.      if(res==NULL) //函数参数传递错误或者是没找到
  13.          printf("Not Find!\n");
  14.      else
  15.          printf("Find!\n");
  16.      if(DeleteListByKey(list,sno,CompareBySno))
  17.          printf("delete success!\n");
  18.      else
  19.          printf("delete fail!\n");
  20.     
  21. }
阅读(764) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~