Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 自訂雜湊表實作:鏈地址法處理衝突

雜湊表把「搜尋」從 O(n) 降到接近 O(1),代價是必須處理兩個鍵映射到同一位置時的衝突。最直觀的處理方式是鏈地址法(separate chaining):每個桶不是單一元素,而是一條 linked list。以下用 C++ 完整實作,並附上扩容用的質數序列。

資料結構設計

#include <string.h>
#include <ctype.h>
#include <malloc.h>    /* malloc() 等 */
#include <limits.h>    /* INT_MAX 等 */
#include <stdio.h>     /* EOF(=^Z 或 F6), NULL */
#include <stdlib.h>    /* atoi() */
#include <io.h>        /* eof() */
#include <math.h>      /* floor(), ceil(), abs() */
#include <process.h>   /* exit() */

/* 函數結果狀態碼 */
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)<=(b))

typedef int Status;   /* Status 是函數型別,其值為狀態碼,如 OK 等 */
typedef int Boolean;

#define NULLKEY 0   /* 0 為無記錄標誌 */
#define N 10        /* 數據元素個數 */
typedef int KeyType; /* 設關鍵字域為整型 */

class ElemType{
  public:
    KeyType key;
    int ord;
    ElemType *next;
    ElemType(KeyType key, int ord){
      this->key  = key;
      this->ord  = ord;
      this->next = NULL;
    }
};

int hashsize[] = {11, 19, 29, 37}; /* 哈希表容量遞增表,一個合適的素數序列 */
int m = 0;                         /* 哈希表表長,全域變量 */

typedef struct
{
  ElemType *elem;   /* 數據元素存儲基址,動態分配陣列 */
  int count;        /* 當前數據元素個數 */
  int sizeindex;    /* hashsize[sizeindex] 為當前容量 */
} HashTable;

#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1

桶陣列用 ElemType* 而非 ElemType,是因為每個桶要能指向一條鏈;hashsize 選用質數是為了讓取模後的分布更均勻,這也是實務上的通用經驗。

初始化與雜湊函數

Status InitHashTable(HashTable *H)
{ /* 操作結果:構造一個空的哈希表 */
  int i;
  (*H).count = 0;          /* 當前元素個數為 0 */
  (*H).sizeindex = 0;      /* 初始存儲容量為 hashsize[0] */
  m = hashsize[0];
  (*H).elem = (ElemType*)malloc(m * sizeof(ElemType));
  if(!(*H).elem)
    exit(OVERFLOW);        /* 存儲分配失敗 */
  for(i = 0; i < m; i++)
    (*H).elem[i].key = NULLKEY;  /* 未填記錄的標誌 */
  return OK;
}

unsigned Hash(KeyType K)
{ /* 一個簡單的雜湊函數(m 為表長,全域變量) */
  return K % m;
}

插入:衝突時掛到鏈尾

Status InsertData(HashTable *H, ElemType e)
{
  int p;
  ElemType *x;
  p = Hash(e.key);

  if ((*H).elem[p].key == NULLKEY){   /* 桶是空的,直接放入 */
    (*H).elem[p] = e;
    ++(*H).count;
  } else {                            /* 有衝突,走訪到鏈尾再掛上 */
    x = &(*H).elem[p];
    while ((*x).next != NULL){
      x = (*x).next;
    }
    (*x).next = &e;
    ++(*H).count;
  }
}

刪除:分頭節點與非頭節點

void DeletData(HashTable *H, ElemType e)
{
  int p;
  ElemType *x;
  p = Hash(e.key);

  if ((*H).elem[p].ord == e.ord){          /* 命中桶頭 */
    if ((*H).elem[p].next == NULL){
      (*H).elem[p].key = NULLKEY;          /* 鏈上只有一個,清空桶 */
    } else {
      (*H).elem[p] = *(*H).elem[p].next;   /* 後繼上移補位 */
    }
    --(*H).count;
  } else {                                 /* 往鏈上找 */
    x = &(*H).elem[p];
    while ((*((*x).next)).ord != e.ord){
      x = (*x).next;
      if ((*x).next == NULL){
        printf("沒有這個\n");
        exit(0);
      }
    }
    (*x).next = (*x).next->next;           /* 跳過該節點 */
    --(*H).count;
  }
}

void DestroyHashTable(HashTable *H)
{ /* 初始條件:哈希表 H 存在。操作結果:銷毀哈希表 H */
  free((*H).elem);
  (*H).elem = NULL;
  (*H).count = 0;
  (*H).sizeindex = 0;
}

主程式

int main(){
  ElemType a(12, 39);
  ElemType b(2, 33);
  ElemType c(1, 23);

  HashTable h;
  InitHashTable(&h);
  InsertData(&h, a);  printf("insert a\n");
  InsertData(&h, b);  printf("insert b\n");
  InsertData(&h, c);  printf("insert c\n");
}

這份實作的已知問題

值得誠實指出幾處:InsertData 把參數 e 的位址 &e 存進鏈上,而 e 是區域變量,函數返回後該位址即失效,這是典型的懸空指標;InsertData 宣告回傳 Status 卻沒有 return;hashsize 定義了扩容序列但沒有實作 rehash;exit(OVERFLOW) 中的 OVERFLOW 未定義。正式專案中應改用 new 配置節點、補上回傳值,並在 count 超過負載因數時觸發扩容與重新雜湊。

注:本代碼參考嚴蔚敏老師的《數據結構》。

Copyright © Linux教程網 All Rights Reserved