标签:
采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。
|
1
|
3,1
|
#include<iostream> #include<cstring> using namespace std; typedef struct node { int data; struct node *next; }Chain; typedef struct { Chain *head[100]; int len, n; }HashTable; Chain * tail[100]; HashTable ha; void InsertHT() { int adr, k; Chain *p = new Chain; cin >> k; adr = k%ha.len; p->data = k; p->next = NULL; if (!ha.head[adr]) { ha.head[adr] = p; tail[adr] = ha.head[adr]; } else { tail[adr]->next = p; tail[adr] = p; } } void CreateHT(int len, int n) { ha.len = len, ha.n = n; for (int i = 0; i < n; i++) ha.head[i] = NULL; for (int i = 0; i < n; i++) InsertHT(); } void Search(int x) { int adr = x%ha.len, flag = 0, cnt = 0; Chain *p = ha.head[adr]; while (p) { cnt++; if (p->data == x) { flag = 1; break; } else p = p->next; } if (flag)cout << adr << ‘,‘ << cnt; else cout << "-1"; } int main() { int len, n, x; cin >> len >> n; CreateHT(len, n); cin >> x; Search(x); return 0; }
标签:
原文地址:http://www.cnblogs.com/traini13/p/4579880.html