哈希表

#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1
#define NULLKEY -1
#define OK 1

#define EQ(x,y) ((x) = (y))
#define LT(x,y) ((x) < (y))
#define LE(x,y) ((x) <= (y))

int hashSize[] = { 997,1999,11999};

typedef struct{
	int key;
	int data;
}ElemType;

typedef struct{
	ElemType * elem;
	int count;
	int sizeindex;
}HashTable;

int hash(int k)
{
	return (k % 1000);
}

void collision(int &p,int&c)
{
	p = hash(p + c*c);
}
int searchHash(HashTable h,int k,int &p,int &c)
{
	p = hash(k);
	while(h.elem[p].key != NULLKEY &&  !EQ(k,h.elem[p].key))
		collision(p,++c);
	if(EQ(k,h.elem[p].key))
		return SUCCESS;
	else return UNSUCCESS;
}
int insertHash(HashTable &h,ElemType e)
{
	int p=0,c=0;
	if(searchHash(h,e.key,p,c))
		return DUPLICATE;
	else if(c < hashSize[h.sizeindex ]/2){
		h.elem[p] = e;
		++h.count;
		return OK;
	}
	else{
		return UNSUCCESS;
	}
}

int main()
{
	HashTable ht;
	ht.sizeindex = 0;
	ht.count = 0;
	ht.elem = (ElemType *)malloc(sizeof(ElemType) * 1000);
	for(int i = 0;i < hashSize[ht.sizeindex];i++)
		ht.elem[i].key = NULLKEY;

	ElemType et = {123,1111};
	insertHash(ht,et);
	int k=124,p=-1,c=0;
	searchHash( ht, k, p, c);
	printf("%d\n",p);

	system("pause");

}

  

原文地址:https://www.cnblogs.com/wuliqun/p/2420100.html