1. 程式人生 > >一步一步寫演算法(之通用資料結構)

一步一步寫演算法(之通用資料結構)

               

【 宣告:版權所有,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】

    上一篇部落格介紹了通用演算法,那麼有了這個基礎我們可以繼續分析通用資料結構了。我們知道在c++裡面,既有資料又有函式,所以一個class就能幹很多事情。舉一個簡單的例子來說,我們可以編寫一個數據的class計算類。

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;}};
    那麼我們可不可以仿造這個思路,在常用的資料結構裡面新增一些函式指標呢?至於為什麼要這些函式指標,主要是因為我們設計的資料結構是通用的資料型別,那麼其中必然有一些譬如compare的函式需要具體資料型別的參與。現在,我們定義一個迴圈佇列,
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;
    那麼QUEUE的建立函式、列印函式有什麼區別嗎?
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;}

    有了函式指標之後,整個資料結構顯得有點複雜。但是我們沒有辦法,這是設計通用資料結構必須花的一個代價。那麼有了這個資料結構之後,如何才能實現對整個佇列的資料列印呢?朋友們可以自己寫一下,再看看我寫的是否正確。

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)通用資料結構有很多好處,寫的越熟,用得越好。