哈希表的各种操作(哈希表的构造,插入元素,删除元素,查找数据元素,打印数据)

#pragma once
#include
using namespace std;

template 
class HashTable;

template 
class BucketNode
{
public:
	friend class HashTable;
	BucketNode():data(Type()),link(NULL){}
	~BucketNode(){}
	BucketNode(Type d,BucketNode *l=NULL):data(d),link(l){}
public:
	BucketNode *link;
	Type data;
};

template 
class HashTable
{
public:
	HashTable(){}
public:
	void Insert(const Type &key)//在散列表中插入值
	{
		int index=Hash(key);
		BucketNode *s=GetNode(key);

		s->link=hashtable[index];
		hashtable[index]=s;
	}
	void Remove(const Type &key)//在散列表中删除值
	{
		int index=Hash(key);
		BucketNode *p=hashtable[index];
		BucketNode *s=p;
		if(p->data==key) //如果是链表的头节点
		{
			hashtable[index]=p->link;
			free(p);
			p=NULL;
			return;
		}
		//说明是中间节点
		while(p)
		{
			if(p->data==key)
			{
				s->link=p->link;
				free(p);
				p=NULL;
				return ;
			}
			s=p;
			p=p->link;
		}
	}
	BucketNode* Find(const Type &key)//在散列表中查找值
	{
		int index=Hash(key);
		BucketNode *p=hashtable[index];
		if(p==NULL)
			return NULL;
		while(p)
		{
			if(p->data==key)
				return p;
			p=p->link;
		}
		return NULL;
	}
public:
	void print()        //打印散列表中的值
	{
		int i;
		for(i=0;i *p=hashtable[i];
			while(p)
			{
				cout<data<<"->";
				p=p->link;
			}
			cout<<"null"<* GetNode(const Type &x) //构造新节点
	{
		BucketNode *p=new BucketNode(x);
		return p;
	}
private:
	enum{HASH_TABLE_SIZE=7};
	static BucketNode* hashtable[HASH_TABLE_SIZE];
};
template
BucketNode* HashTable::hashtable[HASH_TABLE_SIZE]=
{0,0,0,0,0,0,0};

 

你可能感兴趣的:(数据结构之哈希表)