哈希表实现

#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

你可能感兴趣的:(哈希表实现)