阅读背景:

linux内核 hash表的基本使用

来源:互联网 

栗子如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hlist.h"

typedef struct list_test{
    struct hlist_node  hnode;
    int ap;
}HlistTest;

//计算hash值
struct hlist_head * call_hash(struct hlist_head *hash,int id)
{
    unsigned int val = id % 8;
    return &hash[val];
}

int main(int argc,char *argv[])
{
    struct hlist_head *hash;
    struct hlist_node *p = NULL,*n=NULL;
    int i = 0;
    HlistTest  *pNode;
    
	//创建hash表头
    hash = (struct hlist_head *)malloc(sizeof(*hash)*8);
    if(NULL == hash)
    {
        printf("alloc error\n");
        return -1;
    }
    //初始化hash表头 
    for(i = 0; i<8; i++)
        INIT_HLIST_HEAD(&hash[i]);

	//对hash节点赋值	
     for(i = 0; i<100;i++)
     {
         pNode = (HlistTest *)malloc(sizeof(HlistTest));
         if(pNode == NULL)
             continue;
         memset(pNode,0,sizeof(HlistTest));
         INIT_HLIST_NODE(&pNode->hnode);
         pNode->ap = i;
         hlist_add_head(&pNode->hnode, call_hash(hash,i));
     }

     //输出key为3的所有节点
     hlist_for_each_safe(p,n,call_hash(hash,3) ){
          pNode = hlist_entry(p, HlistTest, hnode);
          if(pNode != NULL)
             printf("%d\n",pNode->ap);
     }

	 //删除所有的hash节点
     for(i = 0; i<8;i++)
     {
         p = n = NULL;
         hlist_for_each_safe(p,n,&hash[i])
         {
              pNode = hlist_entry(p, HlistTest, hnode);
              hlist_del(&pNode->hnode);
              free(pNode);
         }
     }
     
	 //节点删除后 看是否还能输出key为3的所有节点
     printf("After delete node\n");
     hlist_for_each_safe(p,n,call_hash(hash,3) ){

          pNode = hlist_entry(p, HlistTest, hnode);
          if(pNode != NULL)
             printf("%d\n",pNode->ap);
     }

out:
    free(hash);
    return 0;
}
	 
	 #include <stdio.h>
#include <std



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: