散列 开放定址法 C实现

头文件

#ifndef _open_hash_h
#define _open_hash_h

#define MINNUM 11
struct Node;
struct HashTbl;
enum kind {legeal,empty,deleted};

typedef struct Node Cell;
typedef struct HashTbl *HashTable;
typedef int Item;

static int hash(Item item,int tableSize);

HashTable initial(int size);
void destroy(HashTable H);
int find(Item item,HashTable H);
void insert(Item item,HashTable H);
void deleteItem(Item item,HashTable H);

#endif



struct Node{
	Item item;
	enum kind info;
};

struct HashTbl{
	int tableSize;
	Cell *theCells;
};

源文件

#include"open_hash.h"

#include
#include



static int hash(Item item,int tableSize){
	return item%tableSize;
}

HashTable initial(int size){
	if(size < MINNUM){
		printf("size too small");
		exit(1);
	}
	
	HashTable H;
	H=malloc(sizeof(struct HashTbl));
	if(H==NULL){
		printf("arrange hashtable fail");
		exit(1);
	}
	H->tableSize=size;
	H->theCells=malloc(sizeof(struct Node)*H->tableSize);
	if(H->theCells==NULL){
		printf("arrange array fail");
		free(H);
		exit(1);
	}
	int i;
	for(i=0;i!=H->tableSize;i++){
		H->theCells[i].info=empty;
	}
	return H;
	
}

void destroy(HashTable H){
	free(H->theCells);
	free(H);
}

int find(Item item,HashTable H){
	int pos=hash(item,H->tableSize);
	int collision=0;
	while(H->theCells[pos].info!=empty && H->theCells[pos].item!=item){
		pos+=2*++collision-1;
		if(pos>=H->tableSize)
		  pos-=H->tableSize; 
	}
	return pos;	
}
void insert(Item item,HashTable H){
	int pos=find(item,H);
	if(H->theCells[pos].info!=legeal){
		H->theCells[pos].info=legeal;
		H->theCells[pos].item=item;
	}
}
void deleteItem(Item item,HashTable H){
	int pos = find(item,H);
	if(H->theCells[pos].info==legeal)
	  H->theCells[pos].info=deleted;
}

测试例程

#include"open_hash.h"

#include
#include

int main(){
	
	HashTable H=initial(17);
	int pos;
	pos=find(6,H);
	if(H->theCells[pos].info ==empty)
	  printf("no such a key\n");
	
	insert(6,H);
	insert(63,H);
	insert(61,H);
	insert(26,H);
	
	pos=find(6,H);
	if(H->theCells[pos].info ==legeal)
	  printf("has such a key\n");
	deleteItem(6,H);
	pos=find(6,H);
	if(H->theCells[pos].info ==deleted)
	  printf("has delete such a key\n");
}


你可能感兴趣的:(数据结构与算法分析,c语言)