1. 程式人生 > >雜湊表的簡單實現例子

雜湊表的簡單實現例子

Hash
// Hash.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
enum {COUNT=17};
typedef int DATA ;
struct SNode
{
	DATA data;
	SNode* pNext;
};
//SNode* g_pHead = NULL; //單條連結串列
SNode* g_pData[COUNT] = {0}; //COUNT個連結串列的頭
int g_nTest[COUNT]; //int個int
void SetAt(const DATA &data)
{
	int n = data%COUNT;//n ->  0-16
	SNode* p = new SNode;
	p ->data = data;
	//新節點的後繼是某條連結串列的原來的頭
	p ->pNext = g_pData[n];//g_pData[n]是一個指標型別SNode*
	g_pData[n] = p;//新的頭節點
}
bool Lookup(const DATA &data)
{
	int n = data%COUNT;
	SNode* p = g_pData[n];
	while(p)
	{
		if(p->data == data)
			return true;
		p = p ->pNext;
	}
	return false;
}
int main(int argc, char* argv[])
{
	int i = g_nTest[5];//的型別是int
	SetAt(889);
	SetAt(1009);
	SetAt(1020);
	SetAt(1023);
	SetAt(1026);
	SetAt(1019);
	SetAt(1087);
	SetAt(1007);
	if(Lookup(1009))
		cout << "找到了" <<endl;
	else
		cout << "未找到" << endl;
	return 0;
}