Hash表(拉链法)

//拉链法建立hash表
//hash.h
#ifndef Hash_H
#define Hash_H

#include <string>

using namespace std;

struct node{
 node():next(NULL){}
 string value;
 node* next;
};

typedef node* HashNode;
const int MULT = 31;
const int TABLE_CAPACITY = 10000;

class Hash{
public:
       Hash(HashNode* table);
       ~Hash();
       void Insert(const string& word);
    int Delete(const string& word);
       int Search(const string& word);
private:
     unsigned int hash(const string& word);//
     HashNode* table;
};

#endif
//hash.cpp

#include "hash.h"
#include <iostream>

using namespace std;

Hash::Hash(HashNode* otherTable)
{
 table=otherTable;
}

Hash::~Hash()
{
 delete[] table;
}

unsigned int Hash::hash(const string& word)
{
 const char* p=word.c_str();
 unsigned int index = 0;
 for (; *p; p++)
 {
  index = (index*MULT)%TABLE_CAPACITY+(*p)%TABLE_CAPACITY;
 }
    return index;
}

void Hash::Insert(const string& word)
{
 int index = hash(word);
   
    if (table[index] == NULL)
    {
  HashNode n =new node();
  n->value=word;
  n->next=NULL;
  table[index]=n;
  return ;
 }
 for (HashNode p=table[index];p;p = p->next)
 {
  if (p->value==word){
   return ;    //已经插入了
  }
 }
  //发成冲突
 HashNode n=new node();
 n->value=word;
 n->next=table[index];
    table[index]=n;
}

int Hash::Delete(const string& word)
{
 int index=hash(word);
 if(!table[index]){
  return -1;
 }
 else{
  HashNode currentNode=table[index];
  HashNode previousNode=currentNode;
  if(currentNode->value==word){
   table[index]=currentNode->next;
   delete currentNode;
   return 1;
  }
  else{
   while(currentNode && currentNode->value!=word)
   {
    previousNode=currentNode;
    currentNode=currentNode->next;
   }
   if(currentNode){
    previousNode->next=currentNode->next;
    delete currentNode;
    return 1;
   }
   return -1;
  }
 }
}

int Hash::Search(const string& word)
{
 int index=hash(word);
 if (table[index]==NULL){
  return -1;
 }
    for (HashNode p = table[index];p!=NULL;p=p->next)
    {
    if (p->value==word)
    {
     return 1;
    }
    }
    return -1;
}

//main.cpp

/*
1.编写一个哈希(Hash)表类,以字符串作为作为关键字存放和查找记录,
提供公共成员函数进行哈希表的记录插入、查询和删除。
并在main函数中测试对该类的使用。
*/

#include "hash.h"
#include <iostream>

using namespace std;

int main(int argc,char** argv)
{
 HashNode myTable[TABLE_CAPACITY] = {NULL};
 Hash* ht = new Hash(myTable);
 ht->Insert("IBM");
 ht->Insert("联想");
 ht->Insert("microsoft");
 ht->Insert("慧谱");
 ht->Insert("慧通");
 ht->Insert("摩托罗拉");
 cout<<"IBM"<< " : "<<ht->Search("IBM")<<endl;
 cout<<"华为"<< " : "<<ht->Search("华为")<<endl;
 cout<<"金山"<< " : "<<ht->Delete("金山")<<endl;
 cout<<"联想"<< " : "<<ht->Delete("联想")<<endl;
 
 return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值