散列 开放定址法 C实现

本文介绍了一种使用开放寻址法实现的散列表的数据结构,并提供了完整的C语言实现代码。该散列表支持插入、查找和删除操作,并采用线性探测解决冲突。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件

#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<stdio.h>
#include<stdlib.h>



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<stdio.h>
#include<stdlib.h>

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");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值