见龙卸甲的经典台词:一步一步写算法(之通用数据结构)

来源:百度文库 编辑:中财网 时间:2024/04/28 19:25:56

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


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

view plaincopy to clipboardprint?

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

view plaincopy to clipboardprint?

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

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

view plaincopy to clipboardprint?

  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. end = pQueue->start;
  8. if(end < pQueue->end)
  9. end = pQueue->end + pQueue->length;
  10. for(index = pQueue->start; index < end; index ++){
  11. pQueue->print(pQueue->head[index % pQueue->length]);
  12. }
  13. return;
  14. }


总结:

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

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