33,008
社区成员
发帖
与我相关
我的任务
分享
//-------------------hash.h-----------
#ifndef __HASH__H
#define __HASH__H
typedef int Status;
#define SUCCESS 1
#define UNSUCCESS 0
//#define DUPLICATE -1
#define INVALID -1 //无数据情况
#define VALID 1 //有数据情况
//#define hashSize 1847
#define hashSize 601
typedef struct node
{
char word[20];
long frequency; //次数
int flag;
struct node* next;
}hashNode;
typedef struct
{
node* pElem;
int count;
int size;
}hashTable;
void CharChange(char *pChar);//character 大写换小写
Status InitHash(hashTable* pHashTable);
Status CreatHash(hashTable* pHashTable, char word[]);
int Coding(char word[]);
#endif
//***************************************************************
//hash.cpp
#include "hash.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void CharChange(char *pChar)
{
char *p;
p = pChar;
while(*p)
{
if (*p>='A' && *p<='Z')
{
*p= (char)(*p + 32);
}
p++;
}
}
Status InitHash(hashTable* pHashTable)
{
int i = 0;
pHashTable->count = 0;//当前元素个数
pHashTable->size = hashSize;//容量
pHashTable->pElem = ( node* )calloc(pHashTable->size, sizeof(node));
if (pHashTable->pElem)
{
for (i=0; i<pHashTable->size; i++)
{
pHashTable->pElem[i].flag = INVALID;
pHashTable->pElem[i].frequency = 0;
pHashTable->pElem[i].next = NULL;
strcpy(pHashTable->pElem[i].word,"");
}
return SUCCESS;
}
else
{
return UNSUCCESS;
}
}
int Coding(char* word)
{
CharChange(word);
char *p;
int num = 0;
int size = hashSize;
p = word;
while ('\0' != *p)
{
num += (int)*p++;
}
return num % size;
}
Status CreatHash(hashTable* pHashTable, char word[])
{
int position = Coding(word);
node *p;
node *pNode;
p = &(pHashTable->pElem[position]);//当前结点地址
if (INVALID == pHashTable->pElem[position].flag)
{
strcpy(pHashTable->pElem[position].word, word);
pHashTable->pElem[position].flag = VALID;
pHashTable->pElem[position].frequency++;
pHashTable->count++;
}
else
{
if(strcmp(pHashTable->pElem[position].word,word) == 0)
{
pHashTable->pElem[position].frequency++;
}
else
{
while (p->next != NULL)
{
p = p->next;
if (strcmp(word,p->word) == 0)
{
p->frequency++;
return SUCCESS;
}
}
if (p->next == NULL)
{
pNode = (node *)malloc(sizeof(node));
if (pNode)
{
strcpy(pNode->word, word);
pNode->next = NULL;
p->next = pNode;
pNode->flag = VALID;
pNode->frequency = 1;
}
else
{
return UNSUCCESS;
}
}
}
}
return SUCCESS;
}