男生要用眼霜吗:一步一步写算法(之通用数据结构)
来源:百度文库 编辑:偶看新闻 时间:2024/04/28 18:43:36
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
上一篇博客介绍了通用算法,那么有了这个基础我们可以继续分析通用数据结构了。我们知道在c++里面,既有数据又有函数,所以一个class就能干很多事情。举一个简单的例子来说,我们可以编写一个数据的class计算类。
view plaincopy to clipboardprint?
- class calculate{
- int m;
- int n;
- public:
- calculate():m(0),n(0) {}
- calculate(int a, int b):m(a),n(b) {}
- ~calculate() {}
- int add() { return m+n; }
- int sub() { return m-n; }
- int mul() { return m *n;}
- int div() { return (n!=0) ?m /n : -1;}
- };
view plaincopy to clipboardprint?
- typedef struct _QUEUE
- {
- int start;
- int end;
- int length;
- int count;
- void** head;
- int (*compare)(void*, void*);
- void (*print)(void*);
- void* (*find)(void*, void*);
- }QUEUE;
view plaincopy to clipboardprint?
- QUEUE* create_new_queue(int length)
- {
- QUEUE* pQueue;
- if(0 == length)
- return NULL;
- pQueue = (QUEUE*)malloc(sizeof(QUEUE));
- assert(NULL != pQueue);
- pQueue->head = (void**)malloc(sizeof(void*)* length);
- assert(NULL != pQueue->head);
- pQueue->start = 0;
- pQueue->end = 0;
- pQueue->count = 0;
- pQueue->length = length;
- pQueue->compare = compare;
- pQueue->find = find;
- pQueue->print = print;
- return pQueue;
- }
有了函数指针之后,整个数据结构显得有点复杂。但是我们没有办法,这是设计通用数据结构必须花的一个代价。那么有了这个数据结构之后,如何才能实现对整个队列的数据打印呢?朋友们可以自己写一下,再看看我写的是否正确。
view plaincopy to clipboardprint?
- void print_value_in_queue(QUEUE* pQueue)
- {
- int index ;
- int end;
- if(NULL == pQueue || 0 == pQueue->count)
- return;
- end = pQueue->start;
- if(end < pQueue->end)
- end = pQueue->end + pQueue->length;
- for(index = pQueue->start; index < end; index ++){
- pQueue->print(pQueue->head[index % pQueue->length]);
- }
- return;
- }
总结:
(1)剩下还有compare、find两个子函数,朋友们可以想想怎么利用?
(2)通用数据结构有很多好处,写的越熟,用得越好。
数据结构算法问题
数据结构算法问题
算法与数据结构
数据结构和算法
数据结构算法 谁会?
数据结构(C语言版)的算法C语言源码
怎样学好数据结构与算法
怎么实现数据结构算法演示?
解释“数据结构+算法=程序”
数据结构和算法不一样吗?
设计一个判断表达式中左右括号是否配对的算法采用()数据结构最佳。
数据结构(类C语言)中算法的”大O表示法”怎么求?
数据结构串匹配十大经典算法
求:数据结构中树的遍历算法
数据结构与算法之间的关系
数据结构:递归求单链表得长度算法
求数据结构 c语言算法代码
数据结构和算法能不能一起学?
怎样熟练掌握研究好算法,数据结构??
关于数据结构search算法的问题
求数据结构简单程序算法!送积分
数据结构算法演示系统译成英文
求《数据结构》严尉敏版 c语言算法源代码
校园咨询算法与数据结构课程设计