测试程序(Windows, C++):
/**
* test dhlist
* cheungmine
*/
#define _CRTDBG_MAP_ALLOC
#include<stdlib.h>
#include<crtdbg.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <windows.h>
#include "dhlist.h"
struct ST {
unsigned char ch;
int this_data;
struct list_head i_list;
int more_data;
struct hlist_node i_hash;
char str_data[32];
int end_data;
} *st;
#define HASHSIZE 0xff
#define LISTSIZE 4096
struct list_head list1;
struct hlist_head hlist[HASHSIZE+1];
unsigned int gethash(int c)
{
return (c & HASHSIZE);
}
int main()
{
int i;
unsigned int hash;
struct list_head *list, *node;
struct hlist_node *hp;
struct hlist_node *hn;
INIT_LIST_HEAD(&list1);
for (hash = 0; hash <= HASHSIZE; hash++) {
INIT_HLIST_HEAD(&hlist[hash]);
}
for(i = 0; i < LISTSIZE; i++) {
struct ST *p = (ST*) malloc(sizeof(*p));
if(!p) {
printf("malloc failed.\n");
break;
}
p->ch = 'a' + i;
sprintf(p->str_data, "data:%d", i);
// 串入长串
list_add(&p->i_list, &list1);
// 串入HASH短串
hash = gethash(p->ch);
printf("ALLOC %x %d %p %u\n", p->ch, i, p, hash);
if (hash > HASHSIZE) {
printf("**********ERROR**********\n");
} else {
hlist_add_head(&p->i_hash, &hlist[hash]);
}
}
// 通过长铁丝遍历
i = 0;
list_for_each(list, &list1) {
struct ST *p = list_entry(list, struct ST, i_list);
printf("%p value %d = %d\n", p, i, (int)p->ch);
i++;
}
printf("total %d \n", i);
printf("通过hash串查找内容'C'的箱子\n");
hash = gethash('c');
hlist_for_each(hp, &hlist[hash]) {
struct ST *p = hlist_entry(hp, struct ST, i_hash);
printf("hlist: %c\n", p->ch);
}
printf("通过hash串查找内容'C'的箱子并删除之\n");
hlist_for_each_safe(hp, hn, &hlist[hash]) {
struct ST *p = hlist_entry(hp, struct ST, i_hash);
printf("hlist_del: %c; %s\n", p->ch, p->str_data);
hlist_del(hp);
}
printf("通过hash串查找内容'C'的箱子\n");
hlist_for_each(hp, &hlist[hash]) {
struct ST *p = hlist_entry(hp, struct ST, i_hash);
printf("hlist: %c\n", p->ch);
}
printf("删除全部节点箱子\n");
list_for_each_safe(list, node, &list1) {
struct ST *p = list_entry(list, struct ST, i_list);
list_del(list);
free(p);
}
// 检测内存泄露
_CrtDumpMemoryLeaks();
return 0;
}
