实现hashmap

Posted libing029

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现hashmap相关的知识,希望对你有一定的参考价值。

/*
*数组下面挂着链表
*/


#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<malloc.h> #include<string.h> #include<memory.h> #define uint32 unsigned int #define size_t unsigned int #define uchar unsigned char uint32 bucknum=16; typedef struct data{ uint32 key; char msg[2]; struct data* next; }DATA; typedef struct{ uint32 len; DATA* data; }BUCKET; BUCKET* buckets=NULL; void initMap(uint32* num,BUCKET* dst){ dst=(BUCKET*)malloc(sizeof(BUCKET)*(*num)); memset(dst,0,sizeof(BUCKET)*(*num)); } uint32 hashKey(uchar* p ,size_t len){ uint32 key=0; for(int i=0;i<len;i++){ key=key*31+*(p+i); } return key; } int mapSize(BUCKET* bucket,size_t len){ int sum=0; for(int i=0;i<len;i++){ sum+=bucket[i].len; } return sum; } void put(BUCKET* bucket,size_t size,uint32 key,DATA* data){ int index=key%size; data->key=key; if(bucket[index].len==0){ bucket[index].data=data; bucket[index].len++; return; }else{ DATA* top = bucket[index].data; DATA* below = bucket[index].data; int count=0; do{ if(below->key==key){ if(count==0){ bucket[index].data=data; data->next=below->next; free(below); below=data; }else{ top->next=data; data->next=below->next; free(below); below=data; free(below); } break; }else{ if(below->next!=NULL){ top=below; below=below->next; }else{ below->next=data; bucket[index].len++; break; } } count++; }while(1); } } void destroy(BUCKET* buck,size_t len){ for(int i=0;i<len;i++){ DATA* bc=buck[i].data; while (bc!=NULL) { DATA* tem=bc; bc=bc->next; free(tem); } } free(buck); } void entryExtend(BUCKET* oldbucket,size_t* newlen,size_t oldlen){ BUCKET* newbucket=NULL; *newlen=(*newlen)<<1; initMap(*newlen,newbucket); for(int i=0;i<oldlen;i++){ DATA* bc=oldbucket[i].data; while (bc!=NULL) { put(newbucket,*newlen,bc->key,bc); bc=bc->next; } } destroy(oldbucket,oldlen); oldbucket=newbucket; } /* void put(BUCKET* bucket,char* key,size_t len,DATA* data){ uint32 k = hashKey(key,len); uint32 index = k % buck_num; data->key=k; if(bucket[index].len==0){ bucket[index].data=data; bucket[index].len++; return; }else{ DATA* top = bucket[index].data; DATA* below = bucket[index].data; int count=0; do{ if(below->key==k){ if(count==0){ bucket[index].data=data; data->next=below->next; free(below); below=data; }else{ top->next=data; data->next=below->next; free(below); below=data; free(below); } break; }else{ if(below->next!=NULL){ top=below; below=below->next; }else{ below->next=data; bucket[index].len++; break; } } count++; }while(1); } } */ int main(){ initMap(&bucknum,buckets); destroy(buckets,bucknum); }

 

以上是关于实现hashmap的主要内容,如果未能解决你的问题,请参考以下文章

201671010432词频统计软件项目报告

HashMap 和 ConcurrentHashMap 的区别

HashMap原理:哈希函数的设计

HashMap深度解析

ArrayList 和 HashMap 的默认大小是多数?

如何将 Parcelable 与 HashMap 一起使用