实现一个简易的HashMap
实现一个键的类型为int,值的类型为int的HashMap
输入一个T,表示操作次数;
之后每行接一个操作,可以包括插入、删除、修改、查询、清空、判断是否有这个键;
因为是刚学完随手敲的,所以功能粗糙。插入不考虑键已经存在的情况。删除、修改、查询不考虑键不存在的情况;
#include "bits/stdc++.h" using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; // 因为int的数据范围为1 << 32 个数。所以把哈希表开到1 << 16从内存和效率上讲比较折中 const int SIZE = 1 << 16; struct Map { int key; int value; Map* next; }*hashtable[SIZE]; int hashCode(int k) { int code = k % SIZE; return code < 0 ? -code : code; } Map* init(int k, int v, Map* next) { Map* point = (Map*)malloc(sizeof(Map)); point->key = k; point->value = v; point->next = next; return point; } void insert(int k, int v) { int id = hashCode(k); hashtable[id] = init(k, v, hashtable[id]); } void update(int k, int v) { int id = hashCode(k); Map* point = hashtable[id]; while (point != NULL) { if (point->key == k) { point->value = v; return; } point = point->next; } } int query(int k) { int id = hashCode(k); Map* point = hashtable[id]; while (point != NULL) { if (point->key == k) { return point->value; } point = point->next; } } bool hasKey(int k) { int id = hashCode(k); Map* point = hashtable[id]; while (point != NULL) { if (point->key == k) { return true; } point = point->next; } return false; } void erase(int k) { int id = hashCode(k); Map* pre = hashtable[id]; if (pre == NULL){ return; } if (pre->key == k) { hashtable[id] = NULL; return; } Map* now = pre->next; while (now != NULL) { if (now->key == k) { pre->next = now->next; free(now); return; } pre = now; now = now->next; } } void clear() { for (int i = 0; i < SIZE; i++) { Map* point = hashtable[i]; Map* next; while (point != NULL) { next = point->next; free(point); point = next; } hashtable[i]=NULL; } } int main() { int T, k, v; char op[10]; scanf("%d", &T); while (T--) { scanf("%s", op); if (strcmp("insert", op) == 0) { scanf("%d%d", &k, &v); insert(k, v); } else if (strcmp("update", op) == 0) { scanf("%d%d", &k, &v); update(k, v); } else if (strcmp("query", op) == 0) { scanf("%d", &k); printf("%d\n", query(k)); } else if (strcmp("hasKey", op) == 0) { scanf("%d", &k); puts(hasKey(k) ? "Yes" : "No"); } else if (strcmp("erase", op) == 0) { scanf("%d", &k); erase(k); } else if (strcmp("clear", op) == 0) { clear(); } } return 0; }