데이터 구조: 해시 표 (잔여 법 제외 - 체인 주소 법)

1853 단어 데이터 구조
#include 
using namespace std;


//         :     
//      :    
typedef struct _NODE
{
	int key;
	struct _NODE* next;
}_NODE;

typedef struct Hash_Table
{
	_NODE* pChainHash[13];
}Hash_Table;

//      
Hash_Table* InitHashTable()
{
	Hash_Table* pHashTable = new Hash_Table;
	memset( pHashTable, 0, sizeof(Hash_Table) );
	return pHashTable;
}

//         
_NODE* FindDataInHash( Hash_Table* pHashTable, int key )
{
	if ( !pHashTable )
		return NULL;
	_NODE* pNode = NULL;
	if ( !(pNode = pHashTable->pChainHash[ key % 13 ] ) )
		return NULL;
	while ( pNode )
	{
		if ( pNode->key == key )
			return pNode;
		pNode = pNode->next;
	}
	return NULL;
}

//         
bool InsertDataToHash( Hash_Table* pHashTable, int key )
{
	if ( !pHashTable ) 
		return false;
	if ( NULL != FindDataInHash( pHashTable, key ) )
		return false;//      
	
	_NODE* pNewNode = new _NODE;
	memset( pNewNode, 0, sizeof( _NODE ) );
	pNewNode->key = key;

	_NODE* pNode = NULL;
	pNode = pHashTable->pChainHash[ key % 13 ];
	if ( !pNode )
	{
		pHashTable->pChainHash[ key % 13 ] = pNewNode;
	}
	else
	{
		while( pNode->next )
		{
			pNode = pNode->next;
		}
		pNode->next = pNewNode;
	}
	return true;
}


//         
bool DeleteDataInHash( Hash_Table* pHashTable, int key )
{
	if ( !pHashTable )
		return false;

	_NODE* pNode = NULL;
	if ( !( pNode = pHashTable->pChainHash[key % 13] ) )//    
		return false;

	if ( pNode->key == key )//       
	{
		pHashTable->pChainHash[key % 13] = pNode->next;
		delete pNode;
		return true;
	}

	_NODE* pPreNode = pNode;//    ,           
	pNode = pNode->next;
	while ( pNode )
	{
		if ( pNode->key == key )
		{
			pPreNode->next = pNode->next;
			delete pNode;
			return true;
		}
		pPreNode = pNode;
		pNode = pNode->next;
	}
	return false;
}

좋은 웹페이지 즐겨찾기