您的位置:首页 > 职场人生

百度面试题及我的解答(4) 补class HashMethod1的代码

2009-11-29 18:06 519 查看
不知道为什么,在校园网提交总失败。

#include "StdAfx.h"
#include "TemplateBuf.h"
#include "HashMethod1.h"

HashMethod1::HashMethod1()
:words_arr(NULL)
,pWordBuf(NULL)
,pStrBuf(NULL)
{}

HashMethod1::~HashMethod1()
{
delete []words_arr;
delete []pWordBuf;
}

bool HashMethod1:: InitHashTbl(int buf_size)
{
words_arr = new WORD_STOR[buf_size];
memset(words_arr, 0, sizeof(WORD_STOR)*buf_size);

pWordBuf = new BUF<WORD_NODE>(1024*1024);
if ( !pWordBuf->InitMemory() ){ return false;}

pStrBuf = new BUF<char>(3*1024*1024);
if ( !pStrBuf->InitMemory() ) {return false;}
return true;
}

bool HashMethod1:: Add(char* str)
{
int i=0;
int size_word = strlen(str);
int sum_str =0;
for ( i = 0; i<size_word; i++)
{
sum_str+=str[i];
}

assert(sum_str<65535);

WORD_NODE *pword_node = pWordBuf->GetMem();
if ( NULL == pword_node )
{
cerr << "memory overflow " << endl;
return false;
}

pword_node->cnt_str=size_word;
pword_node->sum_str=sum_str;
pword_node->next = NULL;
pword_node->str = pStrBuf->GetMem(size_word+1);
if ( NULL == pword_node->str )
{
cerr << "str buffer memory overflow " << endl;
return false;
}
strcpy(pword_node->str, str);
pword_node->str[size_word]=0;

pword_node->sorted_str = pStrBuf->GetMem(size_word+1);
if ( NULL == pword_node->str )
{
cerr << "sorted str buffer memory overflow " << endl;
return false;
}
strcpy(pword_node->sorted_str, str);
pword_node->sorted_str[size_word]=0;
sort(pword_node->sorted_str, pword_node->sorted_str+size_word);

WORD_NODE* pnext = words_arr[sum_str].words_arr_cnt[size_word];
words_arr[sum_str].words_arr_cnt[size_word]=pword_node;
pword_node->next = pnext;
words_arr[sum_str].has_store = true;
return true;
}

void HashMethod1:: TraverseTbl(WORD_LIST_PROCESS_FUNC* pprocessFunc, ostream& out)
{
for (int i = 0; i <65535; i++)
{
if (!words_arr[i].has_store)
{continue;}

for ( int j = 0; j < 26; j++)
{
WORD_NODE *plist = words_arr[i].words_arr_cnt[j];
if ( NULL == plist ){ continue;}
(*pprocessFunc)(plist, out);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐