命令调用先构建hashTable

2023-12-15 18:16:55

GPT 代码改

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABLE_SIZE 256

struct Node {
  char *key;
  void *value;
  struct Node *next;
};

struct HashTable {
  struct Node *table[TABLE_SIZE];
};

void initHashTable(struct HashTable *hashTable) {
  for (int i = 0; i < TABLE_SIZE; i++) {
    hashTable->table[i] = NULL;
  }
}

int hashFunction(char *key) {
  unsigned long hash = 0;
  int c;

  while ((c = *key++)) {
    hash = c + (hash << 6) + (hash << 16) - hash;
  }

  return hash % TABLE_SIZE;
}

void insert(struct HashTable *hashTable, char *key, void *value) {
  int index = hashFunction(key);

  struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
  if (newNode == NULL) {
    fprintf(stderr, "Memory allocation failed\n");
    exit(EXIT_FAILURE);
  }

  newNode->key = strdup(key);
  newNode->value = value;
  newNode->next = NULL;

  newNode->next = hashTable->table[index];
  hashTable->table[index] = newNode;
}

void *get(struct HashTable *hashTable, char *key) {
  int index = hashFunction(key);

  struct Node *current = hashTable->table[index];
  while (current != NULL) {
    if (strcmp(current->key, key) == 0) {
      return current->value;
    }
    current = current->next;
  }
  return 0;
}

void removeKey(struct HashTable *hashTable, char *key) {
  int index = hashFunction(key);

  struct Node *current = hashTable->table[index];
  struct Node *prev = NULL;

  while (current != NULL) {
    if (strcmp(current->key, key) == 0) {
      if (prev == NULL) {
        hashTable->table[index] = current->next;
      } else {
        prev->next = current->next;
      }

      free(current->key);
      free(current);
      return;
    }

    prev = current;
    current = current->next;
  }
}

void freeHashTable(struct HashTable *hashTable) {
  for (int i = 0; i < TABLE_SIZE; i++) {
    struct Node *current = hashTable->table[i];
    while (current != NULL) {
      struct Node *next = current->next;
      free(current->key);
      free(current);
      current = next;
    }
  }
}

void hello() { printf("hello\n"); }
void world() { printf("world\n"); }

int main() {
  struct HashTable hashTable;
  initHashTable(&hashTable);

  insert(&hashTable, "hello", hello);
  insert(&hashTable, "world", world);
  ((void (*)())get(&hashTable, "hello"))();
  freeHashTable(&hashTable);
  return 0;
  }

对驱动来说,别名映射很重要,就像生活不能没有太阳

在这里插入图片描述

修改后

文章来源:https://blog.csdn.net/weixin_45647912/article/details/135020439
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。