哈希表---开散列实现

来源:互联网 发布:lol游戏网络异常 编辑:程序博客网 时间:2024/06/03 12:59
#pragma once#ifndef _HASHTABLE_H_#define _HASHTABLE_H_#include <assert.h>#define defaultSize 100struct Student  {      long ID_number;      char name[12];      char sex;      char address[12];  }; struct ChainNode                                                      //各桶中同义词子表的链结点定义;{Student data;ChainNode *link;ChainNode() : link(NULL) { }ChainNode(const Student& d, ChainNode *next=NULL) : data(d), link(next) { }};class HashTable                                                          //使用开散列法的散列表的类定义;{public:HashTable(int d, int sz=defaultSize){divisor=d; TableSize=sz;ht=new ChainNode*[sz];                                    //创建头结点;assert(ht!=NULL);for(int i=0; i<sz; ++i) {ht[i]=new ChainNode; assert(ht[i]!=NULL);}}~HashTable() {delete [] ht;}bool Search(const long k1, Student& e1)                           //搜索;{ChainNode *p=FindPos(k1);if(p->data.ID_number==k1) {e1=p->data; return true;}else return false;}bool Insert(const Student& e1){long k1=e1.ID_number;int j=k1%divisor;ChainNode *p=ht[j]->link, *pre=ht[j];while(p!=NULL&&p->data.ID_number!=k1) {pre=p; p=p->link;}if(p!=NULL&&p->data.ID_number==k1) return false;p=new ChainNode(e1);pre->link=p;return true;}bool Remove(const long k1, Student& e1){int j=k1%divisor;ChainNode *p=ht[j]->link, *pre=ht[j];while(p!=NULL&&p->data.ID_number!=k1) {pre=p; p=p->link;}if(p!=NULL&&p->data.ID_number==k1){e1=p->data;pre->link=p->link; delete p;return true;}else return false;}private:ChainNode *FindPos(const long k1){int j=k1%divisor;ChainNode *p=ht[j];while(p!=NULL&&p->data.ID_number!=k1) p=p->link;return p;}private:int divisor;                                                                //除数(质数);int TableSize;                                                           //桶数;ChainNode **ht;                                         //散列表的定义;};#endif