博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
手写哈希表
阅读量:3927 次
发布时间:2019-05-23

本文共 2307 字,大约阅读时间需要 7 分钟。

点击上方蓝字关注我,我们一起学编程

欢迎小伙伴们分享、转载、私信、赞赏

微信搜索:编程笔记本

微信搜索:编程笔记本
微信搜索:编程笔记本

是的,在面试深信服的时候,面试官让我 10min 手写哈希表(/微笑)。没错,我没写出来,于是我自己花了 20*10min 自己写了一个简单的哈希表出来。在这里贴出来,小伙伴可以提提意见,交流一波~

#include 
using namespace std;#define MAXSIZE 10 // 哈希值#define UNIONSIZE 100 // 共用体的字符长度/* 哈希表底层链表节点 */template
struct Node {
K key; V value; struct Node* next;};/* 用于计算哈希值的共用体 */template
union Union {
K key; char ch[UNIONSIZE]; Union(K _key) : key(_key) {
}};/* 哈希表类 */template
class HashTable {
private: Node
* node[MAXSIZE]; // 底层链表public: HashTable(); // 构造函数 int hash(const K key); // 哈希函数 Node
* lookup(const K key); // 查找函数 void insert(const K key, const V value); // 插入函数 V get(const K key); // 访问函数};/* 构造函数 *//* 将哈希表底层链表置空 */template
HashTable
::HashTable() { for (int i = 0; i < MAXSIZE; ++i) { node[i] = nullptr; }}/* 哈希函数 *//* 简单地利用共用体进行哈希计算 */template
int HashTable
::hash(const K key) { int hashValue = 0; unsigned int len = sizeof(key) > UNIONSIZE ? UNIONSIZE : sizeof(key); Union
u(key); for (int i = 0; i < len; ++i) { hashValue += u.ch[i]; } return hashValue % MAXSIZE;}/* 查找函数 */template
Node
* HashTable
::lookup(const K key) { Node
* nd; int hashValue = hash(key); for (nd = node[hashValue]; nd != nullptr; nd = nd->next) { if (nd->key == key) { return nd; } } return nullptr;}/* 插入函数 *//* 若键已存在,则更新值;否则创建新的键值对 */template
void HashTable
::insert(const K key, const V value) { Node
* nd = lookup(key); if (nd == nullptr) { int hashValue = hash(key); nd = (Node
*)malloc(sizeof(Node
)); nd->key = key; nd->next = node[hashValue]; node[hashValue] = nd; } nd->value = value;}/* 访问函数 *//* 若键存在,则返回其值;若键不存在,则插入键值对,并将值置为该类型的零值 */template
V HashTable
::get(const K key) { V value = (V)(0); Node
* nd = lookup(key); if (nd == nullptr) { insert(key, value); nd = lookup(key); } return nd->value;}int main(){ HashTable
hashTable; hashTable.insert(1, 100); hashTable.insert(2, 200); cout << hashTable.get(1) << endl; cout << hashTable.get(2) << endl; cout << hashTable.get(3) << endl; return 0;}/*编译运行:jincheng@DESKTOP$ g++ test.cpp -o testjincheng@DESKTOP$ ./test1002000jincheng@DESKTOP$*/

小伙伴们有什么好的点子或者意见,记得参与讨论告诉我哦~

微信搜索:编程笔记本

微信搜索:编程笔记本
微信搜索:编程笔记本

你可能感兴趣的文章
CyclicBarrier && CountDownLatch
查看>>
java.lang.Object
查看>>
mqtt的messageId是怎么回事
查看>>
记一次线上CPU持续飙升的问题排查
查看>>
java.util.Stack
查看>>
java.lang.Class
查看>>
设计模式之恋
查看>>
手写spring
查看>>
使用redis分布式锁实现一个秒杀业务
查看>>
工厂方法模式(Factory Method)
查看>>
抽象工厂(Abstract Factory)模式
查看>>
建造者(Builder)模式
查看>>
java.lang.InheritableThreadLocal
查看>>
oracle定时器定时清理某张表指定日期前的数据
查看>>
第一个go程序连接mysql读取数据
查看>>
一个小示例,对比下go和java
查看>>
struts2 上传excel文件
查看>>
开篇背景
查看>>
一、计算机核心组成及CPU核心组成
查看>>
CPU内存访问设计
查看>>