ADT—散列表

Posted on 2010-03-31 21:30  625747  阅读(281)  评论(0)    收藏  举报

 

代码
#ifndef _MAP_H_
#define _MAP_H_

#include
<iostream>
struct nlist
{
nlist
*next;
int keys;
int value;
};

class Map
{
public:
Map();
~Map();


int GetLength();
nlist
* Insert ( int key,int newValue );
void Delete (int serchKey);
void Retrieve (int serchKey);
nlist
* hashtable_search(int key);

void printfMap();

nlist
*hashtable[101];
protected:
int hashFun ( int key)
{
key
*=key;
key
/=100; //先求平方值,后去掉末尾的两位数
return key%1000; //取中间三位数作为散列地址返回
};
};

#endif

 

代码
#include "map.h"

using std::cout;
using std::endl;

Map::Map ()
{
for (int i = 0;i <= 100;i++)
hashtable[i]
= NULL;
}

Map::
~Map()
{
for(int i=0;i<101;i++)
{
delete hashtable[i];
}
}

nlist
* Map::Insert (int key,int newValue)
{
nlist
*np = new nlist;
int hashval = 0;

hashval
= hashFun (key);
np
->value = newValue;
np
->keys = key;
np
->next = hashtable[hashval];
hashtable[hashval]
= np;
return np;
}

nlist
* Map::hashtable_search(int key)
{
nlist
*np = new nlist;

while(np != NULL)
{
if (key == np->keys)
return np;
else
return NULL;
}
}

void Map::printfMap ()
{
nlist
*np = new nlist;

for (int i =0;i<101;i++)
{
np
= hashtable[i];
while (np )
{
std::cout
<<np->keys<<"\t"<<np->value<<endl;
np
= np->next;
}
}
}

int main()
{
Map m;

m.Insert (
7,343);
m.Insert (
3,56);
m.Insert (
2,6);
m.Insert (
4,65);

m.printfMap();

return 0;
}