首页 > 其他 > 详细

哈希表实现

时间:2015-01-13 16:02:14      阅读:210      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>

#define INT_MIN -65536

struct hashTable
{
	int *table;
	int length;
	
	hashTable(int size):length(size)
	{
		table=new int[size];

		for(int i=0;i<size;i++)
			table[i]=INT_MIN;
	}
};

int hash(hashTable &h,int key)
{
	return key%h.length;
}

void insert(hashTable &h,int key)
{
	int pos=hash(h,key);

	while(h.table[pos]!=INT_MIN)
		pos=(pos+1)%h.length;

	h.table[pos]=key;

}

int search(hashTable &h,int key)
{
	int pos=hash(h,key);

	while(h.table[pos]!=key)
	{
		pos=(pos+1)%h.length;
		if(h.table[pos]==INT_MIN||pos==hash(h,key))
			return -1;
	}
	return 1;
}

void main()
{
	hashTable h(11);
	insert(h,1);
	insert(h,12);

	printf("%d\n",search(h,12));
}



字符串哈希


#include<stdio.h>
#include<string>
using namespace std;


struct hashTable
{
	string *table;
	int length;
	
	hashTable(int size):length(size)
	{
		table=new string[size];

		for(int i=0;i<size;i++)
			table[i]="";
	}
};

int myhash(hashTable &h,string key)
{
	unsigned int hashVal=0;
	int length=key.length();

	for(int i=0;i<length;i++)
	{
		hashVal=(hashVal<<5)+key[i];
	}

	return hashVal%h.length;
}

void insert(hashTable &h,string key)
{
	int pos=myhash(h,key);

	while(h.table[pos]!="")
		pos=(pos+1)%h.length;

	h.table[pos]=key;
}

int search(hashTable &h,string key)
{
	int pos=myhash(h,key);

	while(h.table[pos]!=key)
	{
		pos=(pos+1)%h.length;
		if(h.table[pos]==""||pos==myhash(h,key))
			return -1;
	}
	return pos;
}

void main()
{
	hashTable h(1009);
	insert(h,"hello");
	insert(h,"world");

	printf("%d\n",search(h,"hello"));
	printf("%d\n",search(h,"world"));
	printf("%d\n",search(h,"jiang"));
}

结果

383

565

-1

哈希表实现

原文:http://blog.csdn.net/u013011841/article/details/42676765

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!