C++类实现hash表的抽象数据结构(链式解决冲突)

本文详细介绍了如何使用C++类来实现一个哈希表,特别是通过链表解决哈希冲突的方法。内容包括哈希函数的设计、哈希表的插入、查找和删除操作。通过对C++类的巧妙利用,实现了一个高效且灵活的哈希数据结构。

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

//--------------------------------------------------------------------------
//本例中采用链式解决冲突,便于查找
//hash表适合存储和查找操作
//构建hash要尽量减少冲突,hash表空间开的大一点,用空间换时间
//hash表的一种变种是位图表,stl中的bitmap<>,多用于大数据查找问题
//---------------------------------------------------------------------------

#ifndef _HASH_H
#define _HASH_H
#include<iostream>
using namespace std;

const int HASH_SIZE = 11;
typedef struct linknode{
	int data;
	struct linknode *next ;
}hashnode,*phashnode;

class HASH{
public:
	phashnode initHash();                                        //hash表的初始化
	void createHash(int arr[], int size, phashnode _hash);       //hash表的构建
	int hash_func(int value);                                    //hash函数
	int searchHash(phashnode _hash, int value);                  //hash表的查找
};

phashnode HASH::initHash() {
	int i;
    phashnode myhash= new hashnode[HASH_SIZE];
	if(!myhash) {
		return NULL;
	}
	for(i=0;i<HASH_SIZE;++i) {
		myhash[i].data=-1;
		myhash[i].next=NULL;
	}
	return myhash;
}

int HASH::hash_func(int value) {
	return value%HASH_SIZE;
}

void HASH::createHash(int arr[], int size,phashnode _hash) {
	int i;
	for(i=0;i<size;++i) {
		int key = hash_func(arr[i]);
		phashnode tmp = _hash+key;
		if( -1 == tmp->data ) {
			tmp->data = arr[i];
		}
		else {
			phashnode newnode = new hashnode;
			newnode->data=arr[i];
			newnode->next=NULL;
			while( NULL != tmp->next ) {
				tmp=tmp->next;
			}
			tmp->next=newnode;
		}
	}
}

int HASH::searchHash(phashnode _hash, int value) {
	int key = hash_func(value);
	cout<<"value in hash:"<<_hash[key].data<<endl;
	if( -1 == _hash[key].data ) {
		return -1;
	}
	phashnode tmp=_hash+key;
	while(NULL!=tmp && value != tmp->data ) {
		tmp=tmp->next;
	}
	if(NULL==tmp) {
		return -1;
	}
	else {
		return 1;
	}
}


#endif


#include"hash.h"

int main() {
	int arr[]={1,2,3,4,5,6,7,8,9,13};
	int size=sizeof(arr)/sizeof(int);
	int i;
	int value=13;
	HASH * _hash = new HASH;
	phashnode myhash = _hash->initHash();
	_hash->createHash(arr,size,myhash);
	cout<<_hash->hash_func(value)<<endl;
	for(i=0;i<size;++i) {
		cout<<myhash[i].data<<"  ";
	}
	cout<<""<<endl;
	cout<<_hash->searchHash(myhash,value)<<endl;
	delete _hash;
	_hash=NULL;
	system("pause");
	return 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值