#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就是该原文件本身。