const int P = 13;
const int CAPCITY = 3;
const int DEFAULT_VAL = -1;
class myHash
{
public:
typedef struct buck_node
{
int data[CAPCITY];
struct buck_node* next;
}buck_node;
myHash()
{
buck_node* p = NULL;
for (int i = 0; i < P; ++i)
{
for (int j = 0; j < sizeof(p->data) / sizeof(*(p->data)); ++j)
hash_table[i].data[j] = DEFAULT_VAL;
hash_table[i].next = NULL;
}
}
int getHash(int x)
{
return x%P;
}
void show()
{
for (int i = 0; i < P; ++i)
{
buck_node* cur = &hash_table[i];
cout <<endl<< "P=" << i << ":--> ";
while (cur)
{
cout << "[";
for (int i = 0; i < CAPCITY; ++i)
{
cout << cur->data[i]<<" ";
}
cout << "]->";
cur = cur->next;
}
cout <<"NULL"<< endl;
}
}
void insert(int x)
{
int index = getHash(x);
int pos = x%CAPCITY;
buck_node* cur = &hash_table[index];
while (cur->next && cur->data[pos] != DEFAULT_VAL)
cur = cur->next;
if (cur->data[pos]== DEFAULT_VAL)
cur->data[pos] = x;
else if (cur->next == NULL)
{
cur->next = BuyNode();
cur = cur->next;
cur->data[pos] = x;
}
}
void find(int x)
{
int index = getHash(x);
int pos = x%CAPCITY;
buck_node* cur = &hash_table[index];
int capcount = 1;
while (cur && cur->data[pos] != x)
{
cur = cur->next;
capcount++;
}
if (cur->data[pos] == x)
{
cout << "p:" << index << " capcount:" << capcount << " pos:" << pos;
cout << " is:>" << x << endl;
}
else
{
cout << "not found" << endl;
}
}
void Delete(int x)
{
}
protected:
buck_node* BuyNode()
{
buck_node* p = new buck_node;
for (int i = 0; i < CAPCITY; ++i)
p->data[i] = DEFAULT_VAL;
p->next = NULL;
return p;
}
private:
buck_node hash_table[P];
};
void test()
{
myHash IntHash;
//IntHash.show();
cout << " " << endl;
time_t a;
srand((unsigned)time(&a));
for (int i = 0; i < 3000; ++i)
IntHash.insert(i);
//IntHash.show();
cout << "find(1494) " << endl;
IntHash.find(1494);
}
void main()
{
test();
}
hash table
最新推荐文章于 2023-06-04 19:55:34 发布