• 哈希表,哈希结构,查找


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct Node {
            char *data;
            struct Node *next;
    } Node;
    typedef struct hash_table {
            Node **data;
            int size;
    } hash_table;
    
    hash_table *init_hashtable (int size) {
            hash_table * hash = (hash_table *)malloc(sizeof(hash_table));
            hash->size = size << 1;
            hash->data = (Node **)calloc(hash->size, sizeof(Node *));
            return hash;
    }
    
    void clear_node(Node *p) {
            if (!p) return ;
            Node *q;
            while(p) {
                    q = p->next;
                    free(p->data);
                    free(p);
                    p = q;
            }
            return ;
    }
    
    void clear(hash_table *p) {
            if (!p) return ;
            for (int i = 0; i < p->size; i++) clear_node(p->data[i]);
            free(p->data);
            free(p);
            return ;
    }
    
    Node *init(char *s, Node *p) {
            Node *q = (Node *)malloc(sizeof(Node));
            q->next = p;
            q->data = strdup(s);
            return q;
    }
    
    int BKDRhash(char *s) {
            int seed = 31, hash = 0;
            for(int i = 0; s[i]; i++) hash = hash * seed + s[i];
            return hash & 0x7ffffff;
    }
    
    int seach(char *s, hash_table *p) {
            int ind = BKDRhash(s) % p->size;
            Node *node = p->data[ind];
            while(node && strcmp(node->data, s)) node = node->next;
            if (!node) return -1;
            return ind;
    }
    
    void insert(hash_table *p, char *s) {
            if (!p) return ;
            int ind = BKDRhash(s) % p->size;
            p->data[ind] = init(s, p->data[ind]);
    }
    
    int main() {
            int op;
    #define MAX_N 5
            char s[MAX_N + 5];
            hash_table *hash = init_hashtable(MAX_N);
            for(int i = 0; i < MAX_N; i++) 
                    while (~scanf("%d%s", &op, s))
                    switch (op) {
                            case 1: printf("%s insert hashtable
    ", s); insert(hash, s); break;
                            case 0: printf("%s seach %d
    ", s, seach(s, hash));
                    }
    #undef MAX_N
            return 0;
    }
    
  • 相关阅读:
    百度练习题 统计元音字母
    guess number
    LPTHW 结束了
    大坑
    LPTHW 笨办法学python 40章 类
    LPTHW 笨办法学python 37章 python关键字/关键词介绍
    dis进行反编译
    LPTHW 笨办法学python 33章
    eclipse安装详解以及遇到的问题
    安装eclipse错误Could not create the Java virtual machine
  • 原文地址:https://www.cnblogs.com/hhhahh/p/15073982.html
Copyright © 2020-2023  润新知