现在的位置: 首页 > 综合 > 正文

分离链接法实现哈希表

2013年04月26日 ⁄ 综合 ⁄ 共 1686字 ⁄ 字号 评论关闭

代码通过VS2008编译

/*
 
*@author  : Fisher Wang
 
*@function: Realize a hash table
 
*@date    : 11/4/2013
*/

hash_table.h

#include<iostream>
#include<string>

template<typename T1,typename T2>
void infor(const T1& para1=' ',const T2& para2=' ')
{
    std::cout<<para1<<para2<<std::endl;
    return ;
}

struct HashTable
{
    int element;
    HashTable* p2list;
};
typedef HashTable List;

/*  define hashing way : Hash(x)=xmod10
 *  perfect square number is used for this example
 *  you can also change it
 */
template<typename T>
size_t hash(const T &value)//完全平方数散列
{
    return value%10;
}

HashTable* InitializeTable(int table_size)
{
    HashTable* temp;
    temp = (List*)malloc( sizeof(List)*table_size );
    for (int i=0;i<table_size;++i)
    {
        temp[i].p2list=NULL;
    }
    if (temp)
    {
        infor("get a hash_table,and size is :",table_size);
        return temp;
    }
    else
    {
        infor("initialize table failed!\n",' ');
        return NULL;
    }
}

int Insert(HashTable* p2hash,int val)
{
    if (!p2hash)
    {
        return -1;
    }
    else
    {
        List* temp = &p2hash[hash(val)];
        while( temp->p2list!=NULL )
        {
            temp=temp->p2list;
        }
        temp->element=val;
        temp->p2list = (List*)malloc( sizeof(List) );
        temp->p2list->p2list=NULL;
        return 0;
    }
}
void show_hash_table(HashTable* p2hash,size_t a)
{
    for (size_t i = 0;i<a;++i)
    {
        List* temp = &p2hash[i];
        while(temp->p2list!=NULL)
        {
            std::cout<<temp->element<<' ';
            temp=temp->p2list;
        }
        std::cout/*<<temp->element*/<<std::endl;
    }
    return ;
}

 

 

main.cpp

#include<iostream>
#include "hash_table.h"
#define HashCap 10
int main()
{

    HashTable* hash=InitializeTable(HashCap);
    for (int i = 0;i<10;++i)
    {
        Insert(hash,i*i);
    }
    show_hash_table(hash,HashCap);
    system("pause");
    return 0;
}

 

抱歉!评论已关闭.