刚写好的利益链接法解决冲突问题的hash

第一次学hash,感觉有点难啊!

代码奉上:

#include <iostream>
using namespace std;
struct hash_node
{
	int data;
	hash_node *next;
};

hash_node *Data[100] = {NULL};

int hash_fun(int key)
{
	return key % 9;
}

void insert_data(int key)
{
	int pos = hash_fun(key);
	hash_node *node = new hash_node();
	node->data = key;
	node->next = NULL;
	hash_node *temp = Data[pos];
	if (temp == NULL)
	{
		Data[pos] = node;
	} 
	else
	{
		while (temp && temp->next)
		{
			temp = temp->next;
		}
		temp->next = node;
	}
}

void print()
{
	for (int i = 0; i < 100; ++i)
	{
		if (Data[i])
		{
			cout << i << " : ";
			cout << Data[i]->data << " ";
			hash_node *temp = Data[i]->next;
			while (temp != NULL)
			{
				cout << temp->data << " ";
				temp = temp->next;
			}
			cout << endl;
		}
	}
}

int main()
{
	int a[10]={23,32,53,1,5,67,13,26,92,85};
	for (int i = 0; i < 10; ++i)
	{
		insert_data(a[i]);
	}
	print();
}

posted @ 2010-11-30 21:48  hailong  阅读(186)  评论(0编辑  收藏  举报