哈希表【自己实现】

#include <vector>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace  std;


typedef unsigned int UINT;

int const N=1024;

class Node
{
public:
	char *cstr;
	Node *next;
	Node(){cstr=NULL; next=NULL;}
	//Node &operator=(const Node &n)
	//{
	//	cstr = n.cstr;
	//	next = n.next;
	//}
};

class HashTable
{
public:
	void InsertItem(const char *str);
	UINT SearchItem(const char *str);
	Node node[N];
private:
		

	UINT hashf(const char *str);

};


UINT HashTable::hashf(const char *str)
{
	UINT nHash=0;
	while (*str != '\0')
	{
		nHash += *str++;
	}
	return nHash;
}

void HashTable::InsertItem(const char *str)
{
	UINT nHash = hashf(str);
	nHash %= N;

	Node *pNod=node[nHash].next,*p;
	Node*pNodf=pNod;
	p=pNod;
	while (pNod != NULL)
	{
		pNodf = pNod;
		pNod = pNod->next;
	}
	pNod = new Node;

	pNod->cstr=new char[strlen(str)+1];
	strcpy(pNod->cstr, str);
	node[nHash].next=pNod;

}

UINT HashTable::SearchItem(const char *str)
{
	UINT nHash = hashf(str);
	nHash %= N;

	Node *pNod=node[nHash].next;
	Node *pNodf=pNod;
	if (pNod==NULL)
	{
		return 0;
	}
	while (pNod!=NULL)
	{
		if (strcmp(pNod->cstr,str)==0)
		{
			return 1;
		}
		pNodf = pNod;
		pNod = pNod->next;
	}

	if (pNod==NULL)
	{
		return 0;
	}
}


int main()
{

	HashTable hasht;
	ifstream fs;
	fs.open("main.cpp");
	if (!fs)
	{
		cout<<"fail"<<endl;
		return 1;
	}
	else
		cout<<"ok!"<<endl;
	string s;
	while (fs>>s)
	{
		//cout<<s<<endl;
		hasht.InsertItem(s.c_str());
	}

	vector<string > vs;
	vs.push_back("#include");
	vs.push_back("return");
	vs.push_back("kaka");

	cout<<vs[0]<<" "<<hasht.SearchItem(vs[0].c_str())<<endl;
	cout<<vs[1]<<" "<<hasht.SearchItem(vs[1].c_str())<<endl;
	cout<<vs[2]<<" "<<hasht.SearchItem(vs[2].c_str())<<endl;

	fs.close();

	return 0;
}


哈希表

 

读入的main.cpp就是该原文件本身。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值