1. 程式人生 > >圖 雜湊儲存

圖 雜湊儲存

雜湊儲存

1.開放地址法

雜湊表資料結構

const int NULLKEY = -1;
const int DELKEY = -1;
typedef int KeyType;
struct HashTable
{
 KeyType key;
 int count;
};

雜湊表插入與建立

void InsertHT(HashTable ha[], int &n, int m, int p, KeyType k)
{
 int i, adr;
 adr = k % p;
 if (ha[adr].key == NULLKEY || ha[adr].key ==
DELKEY) { ha[adr].key = k; ha[adr].count = 1; } else { i = 1; do { adr = (adr + 1) % m; i++; } while (ha[adr].key == NULLKEY || ha[adr].key == DELKEY); ha[adr].key = k; ha[adr].count = i; } n++; } void CreateHT(HashTable ha[], int &n, int m, int p, KeyType keys[], int
n1) { for (int i = 0; i < m; i++) { ha[i].key = NULLKEY; ha[i].count = 0; } n = 0; for (int i = 0; i < n1; i++) InsertHT(ha, n, m, p, keys[i]); }

雜湊表查詢與刪除

void SearchHT(HashTable ha[], int m, int p, KeyType k)
{
 int i = 1, adr;
 adr = k % p;
 while (ha[adr].key != NULLKEY &&
ha[adr].key != k) { i++; adr = (adr + 1) % m; } if (ha[adr].key == k) cout << "關鍵字:" << k << " 查詢成功 此次比較次數: " << i << endl; else cout << "關鍵字:" << k << " 查詢失敗 此次比較次數: " << i << endl; } bool DeleteHT(HashTable ha[], int &n, int m, int p, KeyType k) { int adr; adr = k % p; while (ha[adr].key != NULLKEY && ha[adr].key != k) adr = (adr + 1) % m; if (ha[adr].key == k) { ha[adr].key = DELKEY; return true; } else return false; }

2.拉鍊法

雜湊表資料結構

typedef int KeyType;
struct NodeType
{
 KeyType key;
 NodeType *next;
};
struct HashTable
{
 NodeType *firstp;
};

雜湊表插入與建立

void InsertHT(HashTable ha[], int &n, int p, KeyType k)
{
 int adr;
 adr = k % p;
 NodeType *q;
 q = new NodeType;
 q->key = k;
 q->next = NULL;
 if (ha[adr].firstp == NULL)
  ha[adr].firstp = q;
 else
 {
  q->next = ha[adr].firstp;
  ha[adr].firstp = q;
 }
 n++;
}
void CreateHT(HashTable ha[], int &n, int m, int p, KeyType keys[], int n1)
{
 for (int i = 0; i < m; i++)
  ha[i].firstp = NULL;
 n = 0;
 for (int i = 0; i < n1; i++)
  InsertHT(ha, n, p, keys[i]);
}

雜湊表查詢與刪除

void Search(HashTable ha[], int p, KeyType k)
{
 int adr, i = 0;
 adr = k % p;
 NodeType *q;
 q = ha[adr].firstp;
 while (q != NULL)
 {
  i++;
  if (q->key == k)
   break;
  q = q->next;
 }
 if (q != NULL)  cout << "關鍵字:" << k << " 查詢成功  此次比較次數: " << i << endl;
 else  cout << "關鍵字:" << k << " 查詢失敗  此次比較次數: " << i << endl;
}

bool DeleteHT(HashTable ha[], int &n, int m, int p, KeyType k)
{
 int adr;
 adr = k % p;
 NodeType *q, *preq;
 q = ha[adr].firstp;
 if (q == NULL)
  return false;
 if (q->key == k)
 {
  ha[adr].firstp = q->next;
  delete q;
  n--;
  return true;
 }
 preq = q; q = q->next;
 while (q != NULL)
 {
  if (q->key == k)
   break;
  q = q->next;
 }
 if (q != NULL)
 {
  preq->next = q->next;
  delete q;
  n--;
  return true;
 }
 else
  return false;
}