您的位置:首页 > 其它

C 语言设计模式(二) 单链表操作

2008-11-26 22:56 225 查看
需要单独实现 :
void list_element_destroy(struct list *ele)
int list_element_cmp(void* l1 , void* l2)
这两个函数,就可以构成一个通用的list,操作代码

struct list
{
void * datas;
struct list * next;
};

struct list * g_first = NULL;
struct list * create_list_ele(void * data)
{
struct list * lt = (struct list *) malloc( sizeof(struct list));
if(lt) {
lt->next = NULL;
lt->datas = data;
}
return lt;
}
void list_element_destroy(struct list *ele)
{
if(ele) {
//destroy ele->data;
free(ele);
}
}
void list_destroy(struct list * lt)
{
struct list *tmp = lt, *t;
//wirte_lock(list)
while(tmp) {
t = tmp;
tmp = t->next;
list_element_destroy(t);
}
//write_unlock(list)
return ;
}
int list_element_cmp(void* l1 , void* l2)
{
return 0;
}

struct list ** list_find_element( void * data)
{
struct list **p;
for(p = &g_first ; *p ; p = &(*p)->next)
if(list_element_cmp((*p)->datas, data) == 0) {
break;
}
return p;
}
int list_add_element(struct list * ele)
{
int ret = 0 ;
struct list **p;
//write_lock(list);
p = list_find_element(ele->datas);
if(*p) {
ret = -1 ; /* element exist already */
} else {
*p = ele;
}
//write_unlock(list);
return ret;
}
int list_remove_element(struct list *ele)
{
struct list ** tmp;
//write_lock(list)
tmp = &g_first;
while(*tmp) {
if(*tmp == ele) {
*tmp = ele->next;
ele->next = NULL;
//write_unlock
return 0;
}
tmp = &(*tmp)->next;
}
//wirte_unlock
return -1; /* not found */
}

int list_element_idx(struct list * ele)
{
struct list * tmp;
int ret = -1, index = 0;
//read_lock(list)
for(tmp = g_first ; tmp ; tmp = tmp->next, index ++) {
if(list_element_cmp(tmp,ele) == 0) {
ret = index;
break;
}
}
//read_unlock(list)
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: