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


    #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;
    }
    
  • 相关阅读:
    java jmap,jstat等工具的使用
    jvm 参数配置
    python NameError: name 'false' is not defined
    aiflow Global variable explicit_defaults_for_timestamp needs to be on (1) for mysql
    TX 笔试题总结
    POJ 3140 Contestants Division
    POJ 1018 Communication System
    POJ 3260 The Fewest Coin
    Leetcode: Median of two sorted Array
    基础知识 (二)
  • 原文地址:https://www.cnblogs.com/hhhahh/p/15073982.html
Copyright © 2020-2023  润新知