编辑代码

#define MAXSIZE 1000  // 定义散列表的最大长度

typedef struct node {
    int key;
    int value;
    struct node* next;
}node;

typedef struct hashTable {
    node* data[MAXSIZE];
}hashTable;

int hash(int key){
    return key % MAXSIZE;  // 散列函数:key mod MAXSIZE
}

// 添加元素到散列表
void insert(hashTable* ht, int key, int value){
    // 新建结点
    node* p = (node*)malloc(sizeof(node));
    p->key = key;
    p->value = value;
    p->next = NULL;

    // 计算 key 的散列值
    int h = hash(key);

    // 将结点插入散列表中
    if (ht->data[h] == NULL) {
        ht->data[h] = p;
    }
    else {
        node* q = ht->data[h];
        while (q->next != NULL) {
            q = q->next;
        }
        q->next = p;
    }
}
// 在散列表中查找 key 对应的 value
int search(hashTable* ht, int key) {
    int h = hash(key);
    if (ht->data[h] == NULL)
        return -1;
    else {
        node* p = ht->data[h];
        while (p != NULL) {
            if (p->key == key)
                return p->value;
            p = p->next;
        }
        return -1;
    }
}