hash_table.h
//
// Created on 2021/4/14.
//
#ifndef C_HASH_TABLE_H
#define C_HASH_TABLE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
static long long n;
struct hash_table {
char *key;
char *value;
struct hash_table *next;
} __attribute__((__packed__));
struct hash_table *first_point;
struct hash_table *current_point;
/**
* 哈希表根据key,获取值,时间复杂度:O(N)
* @param key 键
* @return 值得类型不确定,理论上可以为任何类型
*/
void *hash_table_get(char *key) {
struct hash_table *temp = first_point;
while (temp != NULL) {
if (temp->key == key) {
return temp->value;
} else {
temp = temp->next;
}
}
return NULL;
}
/**
* 将键值对存入哈希表,时间复杂度:O(1)
* @param key 键
* @param value 值
* @return
*/
int hash_table_put(char *key, char *value) {
struct hash_table *temp_hash_table;
temp_hash_table = (struct hash_table*) malloc(sizeof(struct hash_table));
temp_hash_table->key = key;
temp_hash_table->value = value;
temp_hash_table->next = NULL;
if (current_point == NULL) {
first_point = temp_hash_table;
current_point = temp_hash_table;
} else {
current_point->next = temp_hash_table;
current_point->next->next = NULL;
current_point = current_point->next;
current_point->next = NULL;
}
return 0;
}
/**
* 移除某个键值对
* @param key 键
* @return
*/
//int remove(char *key);
/**
* 哈希表大小,即键的个数,时间复杂度:O(N)
* @return
*/
long long hash_table_size() {
struct hash_table *temp = first_point;
while (temp != NULL) {
n += 1;
temp = temp->next;
}
return n;
}
/**
* 判断哈希表是否为空,时间复杂度:O(1)
* @return
*/
bool hash_table_isEmpty() {
return first_point == NULL;
}
/**
* 哈希表所有键值对打印
* @return
*/
char *toString();
#ifdef __cplusplus
}
#endif
#endif //C_HASH_TABLE_H
main.c
#include <stdio.h>
#include "include/data_struct/hash_table.h"
int main() {
printf("Hello, World!\n");
hash_table_put("1", "2");
hash_table_put("3", "4");
hash_table_put("5", "6");
hash_table_put("8", "9");
hash_table_put("10", "11");
hash_table_put("12", "13");
hash_table_put("17", "18");
char *value = "";
value = hash_table_get("13");
if (value == NULL) {
printf("The hash table value of key is NULL\n");
} else {
printf("The hash table value of key 13 is %s\n", value);
}
printf("The hash table size is %ld\n", hash_table_size());
if (hash_table_isEmpty()) {
printf("The hash table is empty\n");
printf("The hash table is %d\n", hash_table_isEmpty());
} else {
printf("The hash table is not empty\n");
printf("The hash table is %d\n", hash_table_isEmpty());
}
return 0;
}
待续!