進入公司的第一個培訓項目,就是用C語言實現雙向鏈表.這是一個比較基礎的,又是很常用的一個結構.在GTK+中,它會給你提供一個現成的.
以前在大學的時候,鏈表的理論知識經過資料結構的修鍊之後,可謂是比較熟悉的,可是沒有自己實現過,當老大給我布置這麼一個任務的時候,我還是比較茫然的.因為自己太是菜鳥了.今天,我把這個鏈表寫一下,回味和複習.
首先,你要明確鏈表要實現什麼功能,一般就是插入、追加、遍曆、刪除、銷毀等。然後就可以根據這麼功能去實現。而且一個鏈表當中,不但可以插入數位結點,還可以插入字串的結點。下面通過代碼來實現這麼功能。
- dlist.h
- #ifndef _DLIST_H
- #define _DLIST_H
- typedef void* value_type
- typedef void (*ForeachFunc)(void* data, void* ctx);
- typedef void (*NodeDestroyFunc)(void* data, void* destroy_ctx);
- typedef struct _DList DList;
- typdef enum _Ret
- {
- RET_FALSE,
- RET_TRUE
- }Ret;
- DList* dlist_create();
- Ret dlist_append(DList* thiz, value_type data);
- Ret dlist_insert(DList* thiz, size_t index, value_type data);
- Ret dlist_delete(DList* thiz, size_t index, NodeDestroy node_destroy, void* ctx);
- Ret dlist_destroy(DList* thiz, NodeDestroy node_destroy, void* ctx);
- void dlist_foreach(DList* thiz, ForeachFunc print, void* ctx);
- endif /*_DList_H*/
下面是dlist.c的具體實現。
- dlist.c
- #include "dlist.h"
- #incluee <stdlib.h>
- #include <stdio.h>
- #include <assert.h>
- typedef struct _Node
- {
- value_type data;
- struct _Node* next;
- struct _Node* prev;
- }Node;
- struct _DList
- {
- Node* first;
- NodeDestroy node_destroy;
- };
- DList* dlist_create(NodeDestroy node_destroy)
- {
- DList* thiz = (DList*)malloc(sizeof(DList));
- thiz->node_destroy = node_destroy;
- thiz->first = NULL;
- return thiz;
- }
- static Node* dlist_find(DList* thiz, size_t index)
- {
- assert(thiz != NULL);
- Node* iter = thiz->first;
-
- while(index > 0)
- {
- iter = iter->next;
- index--;
- }
-
- return iter;
- }
- Ret dlist_append(DList* thiz, value_type)
- {
- assert(thiz != NULL);
- Node* node = (Node* )malloc(sizeof(Node));
- node->next = NULL;
- node->prev = NULL;
- if(thiz->first == NULL)
- {
- thiz->first = node;
- }
- else
- {
- Node* iter = thiz->first;
- while(iter->next != NULL)
- {
- iter = iter->next;
- }
- iter->next = node;
- node->prev = iter;
- }
-
- return RET_TRUE;
- }
- Ret dlist_insert(DList* thiz, size_t index, value_type data);
- Ret dlist_delete(DList* thiz, size_t index, NodeDestroy node_destroy, void* ctx);
- Ret dlist_destroy(DList* thiz, NodeDestroy node_destroy, void* ctx);
- void dlist_foreach(DList* thiz, ForeachFunc print, void* ctx);
由於要寫的代碼比較多,所以沒有一一寫出來,只是實現一部分。不過思路就是這樣咯。