• c/c++ 哈希表 hashtable


    c/c++ 哈希表 hashtable

    概念:用key去查找value

    实现hash函数有很多方法,本文用除留余数法。

    除留余数法的概念:

    取一个固定的基数的余数,注意不能用偶数,用偶数的话,分布会不均匀

    发生冲突时,用链地址法解决

    图形入图:

    
    #include <stdio.h>
    #include <malloc.h>
    #include <assert.h>
    #include <stdbool.h>
    
    #define ElemType int
    #define P 13
    
    typedef struct HashNode{
      ElemType data;
      struct HashNode* link;
    }HashNode;
    
    typedef HashNode* HashTable[P];
    
    void init_hash(HashTable ht){
      for(int i = 0; i < P; ++i){
        ht[i] = NULL;
      }
    }
    
    int hash(ElemType key){
      return key % P;
    }
    void insert_hash_table(HashTable ht, ElemType x){
      int index = hash(x);
      HashNode* s = (HashNode*)malloc(sizeof(HashNode));
      assert(s != NULL);
      s->data = x;
    
      //头插
      s->link = ht[index];
      ht[index] = s;
    }
    
    void show_hash_table(HashTable ht){
      for(int i = 0; i < P; ++i){
        printf("%d: ", i);
        HashNode* p = ht[i];
        while(NULL != p){
          printf("%d->", p->data);
          p = p->link;
        }
        printf("Nul.
    ");
      }
    }
    HashNode* search_hash_table(HashTable ht, ElemType x){
      int index = hash(x);
      HashNode* p = ht[index];
      while(NULL != p && p->data != x){
        p = p->link;
      }
      return p;
    }
    bool remove_hash_node(HashTable ht, ElemType x){
      HashNode* p = search_hash_table(ht, x);
      if(NULL == p)return false;
    
      int index = hash(x);
      HashNode* q = ht[index];
      if(p == q){
        ht[index] = p->link;
        free(p);
        return true;
      }
      while(q->link != p){
        q = q->link;
      }
      q->link = p->link;
      free(p);
      return true;
    }
    int main(){
    
      HashTable ht;
      init_hash(ht);
    
      ElemType ar[] = {19,14,23,1,68,20,84,27,55,11,10,79};
      int n = sizeof(ar) / sizeof(ElemType);
    
      for(int i = 0; i < n; ++i){
        insert_hash_table(ht, ar[i]);
      }
    
      show_hash_table(ht);
    
      ElemType key = 68;
      HashNode* p = search_hash_table(ht, key);
      if(NULL != p){
        printf("%d
    ", p->data);
      }
    
      remove_hash_node(ht, key);
      show_hash_table(ht);
    
      return 0;
    
    }
    
    

    完整代码

  • 相关阅读:
    Codeforces Round #630 (Div. 2)A~E题解
    2020cug新生赛 An easy problem
    tensorflow.python.framework.errors.NotFoundError: <exception str() failed>错误解决
    将博客搬至CSDN
    2018年北京大学软件工程学科夏令营上机考试
    程序设计题目中的输入输出
    2018北大计算机学科夏令营机试题目
    Pyhton全栈的知识点(5)
    Python全栈的知识点(4)
    Python全栈的知识点(3)
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9479223.html
Copyright © 2020-2023  润新知