哈希函数自我实现(设计哈希映射)

不使用任何内建的哈希表库设计一个哈希映射

设计包含以下内容:

put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
remove(key):如果映射中存在这个键,删除这个数值对。
力扣原题传送

本题我使用的是链地址法解决哈希冲突,vector容器存放哈希节点的地址;

结构体定义:

Node:
在这里插入图片描述

struct Node
{
    
    
	int key;//存放key值
	int val;//存放对应的value
	Node* next;//指向结点的指针
	//自定义参数列表初始化节点
	Node(int key, int val) :key(key), val(val), next(nullptr) {
    
    }
};

类定义:

class MyHashMap {
    
    
public:
	vector<Node*> vec;//用一个存放节点地址的容器充当头结点
	int length = 1000;
	/** Initialize your data structure here. */
	MyHashMap() {
    
    
		//vec = vector<Node*>(length, new Node(-1, -1));//初始化vec容器
		//生成length长度的节点,并初始化key、val域为-1、-1,将其地址依次放入vec中
		vec.resize(length);//给vec分配空间
		vec.assign(length, new Node(-1, -1));
	}

	/** value will always be non-negative. */
	void put(int key, int value) {
    
    
		Node* head = vec[key % length];//哈希函数寻找插入位置
		Node* prevNode = head;//设置前节点
		head = head->next;//head先走一步
		while (head) {
    
    
			if (head->key == key)//说明哈希中存在该节点
			{
    
    
				head->val = value;//更新val值
				return;
			}
			head = head->next;
			prevNode = prevNode->next;
		}
		//出循环,说明没找到这个节点,直接插入
		Node* newNode = new Node(key, value);//初始化该节点key值val值
		prevNode->next = newNode;//将新节点链接到哈希表
	}

	/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
	int get(int key) {
    
    
		Node* head = vec[key % length];//哈希函数寻找位置
		head = head->next;
		while (head) {
    
    
			if (head->key == key) {
    
    
				//找到节点,直接返回
				return head->val;
			}
			else if (head->key == -1)
				return -1;//未找到
			head = head->next;
		}
		return -1;
	}

	/** Removes the mapping of the specified value key if this map contains a mapping for the key */
	void remove(int key) {
    
    
		Node* head = vec[key % length];//哈希函数寻找位置
		Node* prevNode = head;
		head = head->next;//head:先走一步了兄弟!
		while (head) {
    
    
			if (head->key == key) {
    
    
				prevNode->next = head->next;
				return;
			}
			else if (head->key == -1)
				return;
			head = head->next;
			prevNode = prevNode->next;
		}

	}
};

猜你喜欢

转载自blog.csdn.net/Genius_bin/article/details/113392477