天天看點

簡單HashTable(鍊位址法哈希表)

#define P 7
#define NULL_DATA -1
#define BUCKET_NODE_SIZE 3
#include<stdlib.h>
struct bucket_node
{
	int data[BUCKET_NODE_SIZE];
	bucket_node *next;
};
class HashTable
{
public:
	 HashTable()
	{
		for(int i=0;i<P; ++i)
		{
			for(int j=0; j<BUCKET_NODE_SIZE; ++j)
			{
				table[i].data[j]= NULL_DATA;
			}
			table[i].next = NULL;
		}
	}
	int Hash(int x)
	{
		return(x % P);
	}
	void Insert(int x)
	{
		int index =Hash(x);
		for(int i=0; i<BUCKET_NODE_SIZE; ++i)
		{
			if(table[index].data[i]== NULL_DATA)
			{
				table[index].data[i]= x;
				return;
			}
		}
		bucket_node * pn = &table[index];
		while(pn->next != NULL)
		{
			for(int i=0;i<BUCKET_NODE_SIZE; ++i)
			{
				if(pn->next->data[i]== NULL_DATA)
				{
					pn->next->data[i]= x;
					return;
				}
			}
			pn = pn->next;
		}
		pn->next = new bucket_node;
		pn->next->data[0]=x;
		for(int i=1; i<BUCKET_NODE_SIZE; ++i)
		{
			pn->next->data[i]= NULL_DATA;
		}
		pn->next->next = NULL;

	}
	~HashTable()
	{
		bucket_node *pn;
		bucket_node *tem;
		for(int i=0; i<P; ++i)
		{
			pn = table[i].next;
			while(pn != NULL)
			{
				tem =pn;
				delete tem;
				pn = pn->next;
			}
		}
	}
private:
	bucket_node table[P];
};
           

繼續閱讀