日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hash表的创建

發布時間:2025/5/22 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hash表的创建 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

功能:創建一個hash table。假設有處理沖突,則採用再散列法放置該元素

代碼參考《零基礎學數據結構》

代碼例如以下:

root@ubuntu:/mnt/shared/appbox/hash# cat hash.c #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <malloc.h>typedef int KeyType;typedef struct {KeyType key; /* key value */int hi; /* hash counts */ }DataType;typedef struct {DataType *data;int tableSize; /* hash table len */int curSize; /* key value numbers */ }HashTable;void DisplayHash(HashTable *H, int m);/* * H:hash table pointer * m: hashtable len * p: devided numbers * hash: be hashed data (src data) * n: number of key values */ void CreateHash(HashTable *H, int m, int p, int hash[], int n) {int i, sum, addr, di, k = 1;/* k: ?/H->data = (DataType *)malloc(m * sizeof(DataType));if(H->data == NULL){printf("H->data is NULL!\n");return ;}for(i=0; i<m; i++){H->data[i].key = -1;H->data[i].hi = 0;}for(i=0; i<n; i++){sum = 0;addr = hash[i] % p;di = addr;if(H->data[addr].key == -1){H->data[addr].key = hash[i];H->data[addr].hi = 1;printf("[line:%d] addr:%d, i=%d, key=%d\n",__LINE__, addr, i, hash[i]);}else{do{di = (di + k)%m;sum += 1;}while((H->data[di].key != -1));H->data[di].key = hash[i];H->data[di].hi = sum + 1;printf("[line:%d] di:%d, i=%d, key=%d\n",__LINE__, di, i, hash[i]);}}H->curSize = n;H->tableSize = m;DisplayHash(H, m); }void DisplayHash(HashTable *H, int m) {int i;printf("hash index: ");for(i=0; i<m; i++)printf("%-5d", i);printf("\n");printf("key value: ");for(i=0; i<m;i++)printf("%-5d", H->data[i].key);printf("\n");printf("hash times: ");for(i=0; i<m; i++)printf("%-5d", H->data[i].hi);printf("\n"); }int main(int argc, char *argv[]) {int hash[] = {23, 35, 12, 56, 123, 39, 342, 90};int m=11, p=11, n=8, pos;HashTable H;CreateHash(&H, m, p, hash, n);return 0; } root@ubuntu:/mnt/shared/appbox/hash#
輸出結果:

root@ubuntu:/mnt/shared/appbox/hash# ./hash [line:59] addr:1, i=0, key=23 [line:59] addr:2, i=1, key=35 [line:70] di:3, i=2, key=12 [line:70] di:4, i=3, key=56 [line:70] di:5, i=4, key=123 [line:59] addr:6, i=5, key=39 [line:70] di:7, i=6, key=342 [line:70] di:8, i=7, key=90 hash index: 0 1 2 3 4 5 6 7 8 9 10 key value: -1 23 35 12 56 123 39 342 90 -1 -1 hash times: 0 1 1 3 4 4 1 7 7 0 0

總結

以上是生活随笔為你收集整理的hash表的创建的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。