码迷,mamicode.com
首页 > 其他好文 > 详细

利用哈希表实现数据查找

时间:2015-08-13 14:28:42      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

题目:现在有一个用来存放整数的Hash表,Hash表的存储单位称为桶,每个桶能放3个整数,当一个桶中要放的元素超过3个时,则要将新的元素存放在溢出桶中,每个溢出桶也能放3个元素,多个溢出桶使用链表串起来。此Hash表的基桶数目为素数P,Hash表的hash函数对P取模。
#include<iostream>
using namespace std;


#define P 7
#define NULL_DATA -1
#define BUCKET_NODE_SIZE 3


struct bucket_node	
{
	int data[BUCKET_NODE_SIZE];
	struct bucket_node *next;
};
bucket_node hash_table[P];


void InitHashTable(bucket_node(*ht)[P])
{
	for(int i=0; i<P; ++i)
	{
		for(int j=0; j<BUCKET_NODE_SIZE; ++j)
		{
			(*ht)[i].data[j] = NULL_DATA;
		}
		(*ht)[i].next = NULL;
	}
}


int Hash(int X)
{
	return X % P;
}
void insert_new_element(bucket_node(*ht)[P], int x)
{
	
	int index = Hash(x);	
	for (int i = 0; i < BUCKET_NODE_SIZE; i++)
	{
		if ((*ht)[index].data[i] == NULL_DATA)
		{
			(*ht)[index].data[i] = x;
			return;
		}
	}
	bucket_node *s = new bucket_node;
	s = (*ht)[index].next;
	bucket_node *p = &(*ht)[index];
	while(s != NULL)
	{
		for(int i = 0; i < BUCKET_NODE_SIZE; i++)
		{
			if (s->data[i] == NULL_DATA)
			{
				s->data[i] = x;
				//(*ht)[index] = *s;
				return;
			}
		}
		p = s;
		s = s->next;
	 }
	s=new bucket_node;
	p->next= s;
	for(int j = 0; j<BUCKET_NODE_SIZE; ++j)
	{
		s->data[j] = NULL_DATA;
	}
    s->next = NULL;
	for (int i = 0; i < BUCKET_NODE_SIZE;i++)
	if (s->data[i] == NULL_DATA)
	{
		s->data[i] = x;
		return;
	}
}


void main()
{
	InitHashTable(&hash_table);
	int ar[] = {8,15,22,29,36,43,50,7,14,21,28,35,42,49,56,63,70,25,30};
	for(int i=0; i<sizeof(ar)/sizeof(int); ++i)
	{
		insert_new_element(&hash_table,ar[i]);
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

利用哈希表实现数据查找

标签:

原文地址:http://blog.csdn.net/yangshuangtao/article/details/47610761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!