数据结构基础(三)哈希表的实现
来源:互联网 发布:伏羲距今多少年 知乎 编辑:程序博客网 时间:2024/04/27 17:07
#pragma once#include <iostream>#define N 10using namespace std;typedef struct node{int val;struct node *next;}Node;void freeLinklist(Node *&head);void freeLinklist(Node *&head){if (head==NULL){return;}if (head->next==NULL){delete head;head=NULL;return;}Node *pre=head;Node *temp=head->next;while(temp->next!=NULL){delete pre;pre=temp;temp=temp->next;}delete pre;head=NULL;};class Hash{public:Hash(){for(int i=0;i<N;i++){hashTable[i]=NULL;}};~Hash(){for (int i=0;i<N;i++){freeLinklist(hashTable[i]);}};Node* find(int val){int index=val%N;Node *head=hashTable[index];if (head!=NULL){while(head->next!=NULL&&head->val!=val){head=head->next;}if (head->val==val){return head;}return NULL;}return NULL;};Node* insert(int val){int index=val%N;Node *head=hashTable[index];if (head!=NULL){while(head->next!=NULL){head=head->next;}head->next=new Node;head->next->val=val;head->next->next=NULL;return head->next;}head=new Node;head->next=NULL;head->val=val;hashTable[index]=head;return head;};void print(){for (int i=0;i<N;i++){Node *head=hashTable[i];if(head==NULL){cout<<endl;continue;}while(head->next!=NULL){cout<<head->val<<"\t";head=head->next;}cout<<head->val<<endl;cout<<endl;}};bool deleteNode(int val){Node *obj=find(val);if (obj==NULL){return true;}//说明哈希表中有这个节点 Node *head=hashTable[val%N];if (head==obj){hashTable[val%N]=obj->next;delete obj;deleteNode(val);return true;}while(head->next!=obj&&head->next!=NULL){head=head->next;}head->next=obj->next;delete obj;deleteNode(val);return true;}private:Node *hashTable[N];//这是个数组};这是哈希表的一种简单的基于数组的实现,哈希函数选为取余,对哈希表的操作就变成了对链表的操作
0 0
- 数据结构基础(三)哈希表的实现
- 数据结构基础 图的遍历(三) 之 BFS+DFS(非递归实现)
- 数据结构基础(一)栈的实现
- 数据结构基础(二)队列的实现
- 数据结构基础 排序算法(三)算法的稳定性
- C# 实现数据结构(三)
- 数据结构基础笔记(三)【严蔚敏】
- 数据结构基础(三)广义表
- 数据结构学习三(一个简单的队列实现)
- 双向链表的实现---数据结构学习(三)
- 双向链表的实现---数据结构学习(三)
- 《数据结构》线性表的链式表示和实现(三)
- 数据结构基础(18) --哈希表的设计与实现
- 数据结构基础(18) --哈希表的设计与实现
- 数据结构基础(18) --哈希表的设计与实现
- ZMQ源码分析(一)-- 基础数据结构的实现
- 数据结构(三)---单链接的实现
- Java实现简单的数据结构(三)
- 提高网站访问速度的34条军规——————上
- Spring MVC通用URI Template
- 50个Android开发技巧(10 为TextView添加样式)
- storyboard页面切换与传值
- GlassFish开启远程管理
- 数据结构基础(三)哈希表的实现
- MySQL中information_schema是什么
- 多线程编程--异步转同步之CountDownLatch
- 运行后将Form中的Panel居中的设置方法
- Git对象库与对象探究
- jquery from表单提交
- 调停者模式
- eclipse里使用tomcat调试web
- php---下载功能