数据结构_哈希查找

c++ 实现简单的哈希查找

// 查找.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>

#define modlen 13			//mod大小为13
using namespace std;

struct node
{
	int data;
	node *next;
};

class hash_
{
public:
	hash_();
	~hash_();
	void create(int *data, int len);		//将数据写入哈希表
	void add(int number);					//向哈希表中写入一个数
	void display();							//打印哈希表
	void hashsearching(int seekdata);		//在哈希表中查找
private:
	node * hashtable;						
};
hash_::hash_()
{
	hashtable = new node[modlen];			
	for (int i = 0; i < modlen; i++)
	{
		hashtable[i].data = 0;
		hashtable[i].next = NULL;
	}										//哈希表初始化
}
hash_::~hash_()
{
}
void hash_::create(int * data, int len)
{
	node *newnodep;
	int position;
	for (int i = 0; i < len; i++)
	{
		position = data[i] % modlen;

		newnodep = new node;
		newnodep->data = data[i];
		newnodep->next = NULL;

		if (hashtable[position].data == 0)			//为0表示该坐标没有元素
		{
			hashtable[position].data = 1;
			hashtable[position].next = newnodep;
		}
		else
		{
			newnodep->next = hashtable[position].next;
			hashtable[position].next = newnodep;
		}
	}
}
void hash_::add(int number)
{
	node *searchp, *followp, *newnodep;
	int position = number % modlen;
	newnodep = new node;
	newnodep->data = number;
	newnodep->next = NULL;
	if (hashtable[position].data == 0)
	{
		hashtable[position].data = 1;
		hashtable[position].next = newnodep;
	}
	else
	{
		newnodep->next = hashtable[position].next;
		hashtable[position].next = newnodep;
	}
}
void hash_::display()
{
	node *searchp;
	for (int i = 0; i < modlen; i++)
	{
		searchp = hashtable[i].next;
		cout << i << " ";
		if (hashtable[i].data == 1)
		{
			while (searchp)
			{
				cout << searchp->data << "->";
				searchp = searchp->next;
			}
		}
		else
			cout << "无数据!";
		cout << endl;
	}
}
void hash_::hashsearching(int seekdata)
{
	int position, count = 1;
	position = seekdata % modlen;
	node *searchp;
	searchp = hashtable[position].next;
	while (searchp != NULL)
	{
		if (searchp->data == seekdata)
		{
			cout << "已找到" << seekdata << "位于" << position << "坐标" << "第" << count << "个" << endl;
			return;
		}
		count++;
		searchp = searchp->next;
	}
	cout << "未找到该数据!" << endl;
}
int main()
{
	int data[100] = {18, 62, 60, 43, 67, 90, 54, 46, 75};
	hash_ h =  hash_();
	h.create(data, 9);
	h.add(26);
	h.add(28);
	h.display();
	h.hashsearching(67);
	system("pause");
    return 0;
}



猜你喜欢

转载自blog.csdn.net/juyuyh/article/details/79107622