06 数据结构与算法之哈希表(拉链法) (C语言实现)

注:只给出C语言实现代码,涉及到的数据结构相关概念请自行阅读相关书籍或参考其他博文;

将哈希表理解为一个顺序表,顺序表里面存储的是一个链表(拉链法解决碰撞)

注:(hash & 0x7FFFFFFF)的作用:让hash值一直保持为正。
Because -1 % 10 == -1 which you certainly don’t want for indexing into an array. Forcing the sign bit to 0 avoids this problem.

  • 0x7FFFFFFF (int)is 0111 1111 1111 1111 1111 1111 1111 1111 : all 1 except the sign bit.
  • (hash & 0x7FFFFFFF) will result in a positive integer.
  • (hash & 0x7FFFFFFF) % tab.length will be in the range of the tab length.

存储字符串版的哈希表 +拉链法解决碰撞

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
    char *str;
    struct Node *next;
}Node;//拉链法处理冲突

typedef struct HashTable{//哈希表结构本质是一个顺序表(一维数组)
  //若顺序表里面存的是Node,则需用Node *指针去接收,若存的是 Node *的地址,则需要用Node **(二维数组)去接收Node *的地址.(顺序表里面存储intsg)
    Node **data;//顺序表每个节点存的是一个链表,用Node *表示,即存储的是每个链表的首地址。所以需要Node **data来接收Node *的地址,顺序表初始化存int *data
    int size;
}HashTable;

Node *init_node(char *str, Node *head){//head记录整个链表的第一个节点
    Node *p = (Node *)malloc(sizeof(Node));
    p->str = strdup(str);//(深拷贝)拷贝了一份传进的字符串,并返回首地址,用完原字符串后会被释放,浅拷贝相当于定义一个 char *p = str,记录该字符串地址,若str被释放了,则p会指向空地址,出现报错。深拷贝就是再复制一份数据,原数据是否被释放与现在需要操作的数据无关,也不会影响原来的数据
    p->next = head;//头插法
    return p;
}
HashTable *init_hashtable(int n){//哈希表的初始化,n为容量
    HashTable *h = (HashTable *)malloc(sizeof(HashTable));
    h->size = (n << 1);//容量扩大一倍 70%-90%就是好的,本次利用率为50%
    h->data = (Node **)calloc(h->size, sizeof(Node *));//每个元素存储的是一个链表的头节点的地址,即为一个指针。calloc向堆区申请空间,并将这片空间清空,存的地址默认为NULL
    return h;
}
int BKDRHash(char *str){//映射为正整数的整型值  (APHash)
    int seed = 31, hash = 0;//种子要为素数
    for(int i = 0; str[i]; i++) hash = hash * seed + str[i];
    return hash & 0x7fffffff;//负数映射为正整数的(int)整型值
}
int insert(HashTable *h, char *str){
    int hash = BKDRHash(str);//需要哈希函数映射为整型值
    int ind = hash % h->size;//
    h->data[ind] = init_node(str, h->data[ind]);//将该字符串存到当前哈希表的第ind位置的存储空间下,即将当前字符串插入到第ind的链表中
    return 1;
}
int search(HashTable *h, char *str){//在h中查找str
    int hash = BKDRHash(str);//将字符串地址映射为整型值
    int ind = hash % h->size;
    Node *p = h->data[ind];//链表的头节点
    while(p && strcmp(p->str, str)) p = p->next;//strcmp相同返回0,即查到时返回0
    return p  != NULL;
}
void clear_node(Node *head){//销毁链表
    if(head == NULL) return;
    Node *p = head, *q;
    while(p){
        q = p->next;
        free(p->str);//前面malloc申请一片空间,并将字符串深拷贝到了该空间上,并返回了该片空间的首地址,需要主动释放strdup拷贝过来的数据域
        free(p);
        p = q;
    }
    return;
}
void clear(HashTable *h){//回收哈希表
    if(h == NULL) return;
    for(int i = 0; i < h->size; i++){
        clear_node(h->data[i]);//释放对应位置的链表
    }
    free(h->data);//再释放h->data数据域
    free(h);//再释放哈希表
    return ;
}
int main(){
    int op;
    #define MAX_N 100 //要查找的字符串长度不超过100
    char str[MAX_N + 5] = {0};
    HashTable *h = init_hashtable(MAX_N);
    while(~scanf("%d%s", &op, str)){//循环输入一个操作方法与字符串
        switch(op){
            case 0:
                printf("insert %s to HashTable\n", str);
                insert(h, str);
                break;
            case 1:
                printf("search %s from the HashTable resulet = %d\n", str, search(h, str));
                break;
        }
    }
    
    #undef MAX_N
    clear(h);
    return 0;
}
//编译 gcc HashTable.cc
//执行 ./a.out
//0 hello
//0 nihao
//0 haha
//1 nihao
//1 nnhao
//ctrl + c结束
  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是C语言实现哈希表(链地址)的代码示例: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_TABLE_SIZE 100 // 定义哈希表中的节点 typedef struct Node { char* key; char* value; struct Node* next; } Node; // 初始化哈希表 void initHashTable(Node** hashTable) { int i; for (i = 0; i < MAX_TABLE_SIZE; i++) { hashTable[i] = NULL; } } // 计算哈希值 int hash(char* key) { int hashValue = 0; while (*key) { hashValue = (hashValue << 5) + *key++; } return hashValue % MAX_TABLE_SIZE; } // 插入节点 void insertNode(Node** hashTable, char* key, char* value) { int hashValue = hash(key); Node* newNode = (Node*)malloc(sizeof(Node)); newNode->key = strdup(key); newNode->value = strdup(value); newNode->next = hashTable[hashValue]; hashTable[hashValue] = newNode; } // 查找节点 char* findValueByKey(Node** hashTable, char* key) { int hashValue = hash(key); Node* node = hashTable[hashValue]; while (node != NULL) { if (strcmp(node->key, key) == 0) { return node->value; } node = node->next; } return NULL; } // 删除节点 void deleteNode(Node** hashTable, char* key) { int hashValue = hash(key); Node* node = hashTable[hashValue]; Node* prevNode = NULL; while (node != NULL) { if (strcmp(node->key, key) == 0) { if (prevNode == NULL) { hashTable[hashValue] = node->next; } else { prevNode->next = node->next; } free(node->key); free(node->value); free(node); return; } prevNode = node; node = node->next; } } // 打印哈希表 void printHashTable(Node** hashTable) { int i; printf("----- Hash Table -----\n"); for (i = 0; i < MAX_TABLE_SIZE; i++) { Node* node = hashTable[i]; printf("[%d]: ", i); while (node != NULL) { printf("(%s, %s) ", node->key, node->value); node = node->next; } printf("\n"); } printf("----------------------\n"); } // 主函数 int main() { Node* hashTable[MAX_TABLE_SIZE]; initHashTable(hashTable); // 插入节点 insertNode(hashTable, "apple", "red"); insertNode(hashTable, "banana", "yellow"); insertNode(hashTable, "grape", "purple"); insertNode(hashTable, "orange", "orange"); insertNode(hashTable, "watermelon", "green"); // 打印哈希表 printHashTable(hashTable); // 查找节点 char* value = findValueByKey(hashTable, "banana"); if (value != NULL) { printf("The value of banana is %s\n", value); } else { printf("Cannot find the node\n"); } // 删除节点 deleteNode(hashTable, "orange"); // 打印哈希表 printHashTable(hashTable); return 0; } ``` 以上就是C语言实现哈希表(链地址)的代码示例,其中包括了插入节点、查找节点、删除节点和打印哈希表等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值