哈希表的线性探查法搜索算法

#include<iostream>
#include<iomanip>
using namespace std;

const int P = 7;
const int DefaultSize = 7;
enum KindOfStatus{Active,Empty,Deleted};

class HashTable
{
public:
	HashTable(const int d,int sz = DefaultSize)
	{
		divitor =d;
		TableSize = sz;
		CurSize = 0;
		ht = new int[TableSize];
		info = new KindOfStatus[TableSize];
		for (int i=0;i<TableSize;++i)
		{
			info[i]= Empty;
		}
	}
	~HashTable()
	{
		delete []ht;
		delete []info;
	}
public:
	int Hash(const int &key)
	{
		int index = key % divitor;
		if (info[index] == Empty)
			return index;
		if (info[index]== Active && ht[index] == key)
			return index;

		int i=index;
		
		do
		{
			i=(i+1) % TableSize;
			if (info[i] == Empty)
				return i;
			if (info[i] ==Active && ht[i]== key)
				return i;
		}while(i != index);
		return i;
	}

	void Show()
	{
		cout<<setw(7)<<"info:";
		for(int i=0; i<TableSize; ++i)
		{
			if (info[i] == Active)
				cout<<setw(4)<<"A";
			else if (info[i] == Empty)
				cout<<setw(4)<<"E";
			else
				cout<<setw(4)<<"D";
		} 
		cout<<endl;
		cout<<setw(7)<<"value:";
		for (i=0;i<TableSize; ++i)
		{
			if (info[i] ==Active)
				cout<<setw(4)<<ht[i];
			else
				cout<<setw(4)<<" ";
		}
		cout<<endl;
		cout<<setw(7)<<"ht:";
		for (i=0;i<TableSize;++i)
		{
			cout<<setw(4)<<i;
		}
		cout<<endl;
	}
	
	void Insert(const int &key)
	{
		int index =Hash(key);

		if (info[index] == Active && ht[index] == key)
		{
			cout<<"元素存在,不能插入!"<<endl;
			return;
		}
		if (info[index]== Active)
		{
			cout<<"表满,不能插入!"<<endl;
			return;
		}
		else
		{
			ht[index] = key;
			info[index]= Active;
			CurSize++;
		}
	}
	int Find(const int &key)
	{
		int index=Hash(key);
		if (info[index] ==Empty)
		{
			cout<<"此位置空,无元素,不能查找!"<<endl;
				return 0;
		}
		if (info[index]==Active && ht[index] == key)
		{
			cout<<"index="<<index<<endl;	
			return index;
		}
		else
		{
			cout<<"表中无此元素!"<<endl;
			return 0;
		}
	}

	void Remove(const int &key)
	{
		int i=Find(key);
		
		if (info[i] ==Empty)
		{
			cout<<"此位置空,无元素,不能删除!"<<endl;
			   return;
		}
		if (info[i] == Active && ht[i] == key)
		{
			info[i] = Deleted;
			CurSize--;
		}
		else
		{
			cout<<"表中无此元素,无法删除!"<<endl;
		}
	}

	void MakeEmpty()
	{
		for (int i=0;i<TableSize;++i)
		{
			info[i] = Empty;
			CurSize =0;
		}

	}
private:
	int divitor;
	int TableSize;
	int CurSize;
	int *ht;
	KindOfStatus *info;
};

void main()
{
	HashTable ht(P);
	ht.Insert(1);
	ht.Insert(2);
	ht.Insert(8);
	ht.Insert(15);
    //ht.Insert(22);
	ht.Show();
	ht.Find(8);
	ht.Show();
	ht.Remove(15);
	ht.Show();
	ht.MakeEmpty();
	ht.Show();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值