数据结构——简单Hash Table实现
来源:互联网 发布:mysql.sock下载 编辑:程序博客网 时间:2024/05/17 22:17
hash-table 在SGI-STL中是提供了的一个模板类,但是VC 6.0中支持的STL却并不是使用SGI-STL,因此也没有不能直接使用hash-table了。
hash最重要的一点就是牺牲空间换取时间,通常要采用一个很大的数组。这点有些像是内联函数(inline),也是空间换时间实现。
这里给出一个简单的hash-table的实现,本来准备用模板写,但是懒得去整理,达到自己的目的就算了。
实现源码为:
//hash_table.h
#ifndef _HASH_TABLE_H_
#define _HASH_TABLE_H_
#include <string>
using namespace std;
struct node
{
node():_next(NULL)
{
}
//string _key;
string _value;
node* _next;
};
typedef node* hash_node;
const int MULT = 31;
const int TABLE = 10000;
class hash_table
{
public:
hash_table(hash_node* table);
~hash_table();
public:
void Insert(const string& word);
//hash_node Search(const string word);
int Search(const string& word);
private:
unsigned int hash(const string& word);
private:
hash_node* _table;
};
#endif //~_HASH_TABLE_H_
//hash_table.cpp
#include "hash_table.h"
#include <iostream>
using namespace std;
hash_table::hash_table(hash_node* table)
{
_table = table;
}
hash_table::~hash_table()
{
delete[] _table;
}
unsigned int hash_table::hash(const string& word)
{
const char* p = word.c_str();
unsigned int h = 0;
for (; *p; p++)
{
h = (h*MULT) % TABLE + (*p) % TABLE;
}
return h;
}
void hash_table::Insert(const string& word)
{
int h = hash(word);
//new item,insert directly
if (_table[h] == NULL)
{
hash_node n = new node();
n->_value = word;
n->_next = NULL;
_table[h] = n;
return ;
}
for (hash_node p = _table[h];p != NULL;p = p->_next)
{
if (p->_value == word)
{
return ; //已经插入了
}
}
//没有插入,但是发成了冲突
hash_node n = new node();
n->_value = word;
n->_next = _table[h];
_table[h] = n;
}
int hash_table::Search(const string& word)
{
int h = hash(word);
if (_table[h] == NULL)
{
return -1;
}
for (hash_node p = _table[h];p != NULL;p = p->_next)
{
if (p->_value == word)
{
return 1;
}
}
return -1;
}
测试程序为:
//main.cpp
#include "hash_table.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
hash_node bin[TABLE] = {NULL};
hash_table* ht = new hash_table(bin);
ht->Insert("IBM");
ht->Insert("金山");
ht->Insert("microsoft");
ht->Insert("ATC");
ht->Insert("dsgg");
ht->Insert("MSRA INTERN");
cout<<"ATC"<< " : "<<ht->Search("ATC")<<endl;
cout<<"华为"<< " : "<<ht->Search("华为")<<endl;
cout<<"金山"<< " : "<<ht->Search("金山")<<endl;
return 0;
}
- 数据结构——简单Hash Table实现
- C++简单实现hash table
- 数据结构—散列表(Hash table,也叫哈希表)
- 【数据结构】哈希表 Hash Table
- 数据结构 : Hash Table
- 数据结构之hash表,HashMap简单实现
- Hash表——The Hash table
- 数据结构基础-Hash Table详解
- 数据结构基础-Hash Table详解
- 【数据结构和算法】Hash Table
- 【数据结构与算法】Hash Table
- [数据结构]Hash Table(哈希表)
- Hash Table 的实现
- 实现数据结构Hash表
- hash table——散列表
- 数据结构之---散列表(hash table)
- hash表简单实现
- 简单实现hash存储
- Meta的作用
- 曼托瓦尼乐团
- 在Win32命令行启动SWT程序
- js: 清空文件输入框的值
- Excel:做个单词默写本
- 数据结构——简单Hash Table实现
- 2007年做个什么样的网站赚钱呢?
- 一个简单的页面扫描程序Scan
- 广州之行
- N多的红烧茄子做法!
- Shift键—轻松把Excel表格转换为图片
- 如何正规的快速建立赚钱的网站
- 给初学者:VB如何操作WEB页的浏览提交———三:学会拨号和断开,内容想发就发,别拿IP限制我!
- 老黄历用语解释