一步一步写算法(之通用数据结构)

来源:互联网 发布:nginx 域名配置 ip 编辑:程序博客网 时间:2024/05/15 23:48

原贴地址:http://blog.csdn.net/feixiaoxing/article/details/6957546

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】


    上一篇博客介绍了通用算法,那么有了这个基础我们可以继续分析通用数据结构了。我们知道在c++里面,既有数据又有函数,所以一个class就能干很多事情。举一个简单的例子来说,我们可以编写一个数据的class计算类。

[cpp] view plaincopy
  1. class calculate{  
  2.     int m;  
  3.     int n;  
  4. public:  
  5.       
  6.     calculate():m(0),n(0) {}  
  7.     calculate(int a, int b):m(a),n(b) {}  
  8.     ~calculate() {}  
  9.   
  10.     int add() { return m+n; }  
  11.     int sub() { return m-n; }  
  12.     int mul() { return m *n;}  
  13.     int div() { return (n!=0) ?m /n : -1;}  
  14. };  
    那么我们可不可以仿造这个思路,在常用的数据结构里面添加一些函数指针呢?至于为什么要这些函数指针,主要是因为我们设计的数据结构是通用的数据类型,那么其中必然有一些譬如compare的函数需要具体数据类型的参与。现在,我们定义一个循环队列,

[cpp] view plaincopy
  1. typedef struct _QUEUE  
  2. {  
  3.     int start;  
  4.     int end;  
  5.     int length;  
  6.     int count;  
  7.     void** head;  
  8.   
  9.     int (*compare)(void*, void*);  
  10.     void (*print)(void*);  
  11.     void* (*find)(void*, void*);  
  12. }QUEUE;  
    那么QUEUE的创建函数、打印函数有什么区别吗?
[cpp] view plaincopy
  1. QUEUE* create_new_queue(int length)  
  2. {  
  3.     QUEUE* pQueue;  
  4.     if(0 == length)  
  5.         return NULL;  
  6.   
  7.     pQueue = (QUEUE*)malloc(sizeof(QUEUE));  
  8.     assert(NULL != pQueue);  
  9.   
  10.     pQueue->head = (void**)malloc(sizeof(void*)* length);  
  11.     assert(NULL != pQueue->head);  
  12.   
  13.     pQueue->start = 0;  
  14.     pQueue->end = 0;  
  15.     pQueue->count = 0;  
  16.     pQueue->length = length;  
  17.       
  18.     pQueue->compare = compare;  
  19.     pQueue->find = find;  
  20.     pQueue->print = print;  
  21.     return pQueue;  
  22. }  

    有了函数指针之后,整个数据结构显得有点复杂。但是我们没有办法,这是设计通用数据结构必须花的一个代价。那么有了这个数据结构之后,如何才能实现对整个队列的数据打印呢?朋友们可以自己写一下,再看看我写的是否正确。

[cpp] view plaincopy
  1. void print_value_in_queue(QUEUE* pQueue)  
  2. {  
  3.     int index ;  
  4.     int end;  
  5.     if(NULL == pQueue || 0 == pQueue->count)  
  6.         return;  
  7.   
  8.     end = pQueue->start;  
  9.     if(end < pQueue->end)  
  10.         end = pQueue->end + pQueue->length;  
  11.   
  12.     for(index = pQueue->start; index < end; index ++){  
  13.         pQueue->print(pQueue->head[index % pQueue->length]);  
  14.     }  
  15.   
  16.     return;  
  17. }  


总结:

    (1)剩下还有compare、find两个子函数,朋友们可以想想怎么利用?

    (2)通用数据结构有很多好处,写的越熟,用得越好。


0 0