文章标题

来源:互联网 发布:淘宝天猫评价提取工具 编辑:程序博客网 时间:2024/06/05 02:49

简单Hash实现

原理

参考《算法导论》p143

coding

#ifndef __HASH_H__#define __HASH_H__#include <iostream>using namespace std;#define HASHSIZE 100class ListNode{public:    int key;    int value;    ListNode *next;    ListNode(){}    ListNode(int k,int v,ListNode *n = NULL):key(k),value(v),next(n){}};class Hash{private:    ListNode **hashmap;    int hash_func(int key);public:    Hash();    ~Hash();    ListNode* FindNode(int key);    void InsertNode(ListNode *node);    void DeleteNode(ListNode *node);    int operator [] (int index);};#endif // __HASH_H___
#include "hash.h"Hash::Hash(){    hashmap = new ListNode*[HASHSIZE];    for(int i = 0;  i < HASHSIZE; i++)    {        hashmap[i] = NULL;    }}Hash::~Hash(){    for(int i = 0; i < HASHSIZE; i++)    {        ListNode *head = hashmap[i];        ListNode *p = head;        while(head)        {            p = head->next;            delete head;            head = p;        }        delete hashmap[i];        hashmap[i] = NULL;    }    delete [] hashmap;    hashmap = NULL;}int Hash::operator[](int index){    ListNode* p = FindNode(index);    return p->value;}int Hash::hash_func(int key){    return key%HASHSIZE;}ListNode* Hash::FindNode(int key){    ListNode *p = hashmap[hash_func(key)];    while(p)    {        if(p->key == key) break;        p = p->next;    }    return p;}void Hash::InsertNode(ListNode *node){    ListNode *f = FindNode(node->key);    if(f)//如果节点存在,直接更新    {        f->value = node->value;        return;    }    else    {         ListNode *p = hashmap[hash_func(node->key)];         while(p && p->next)//索引到地址末端         {             p = p->next;         }         if(p) p->next = node;//在末尾添加         else            hashmap[hash_func(node->key)] = node; //地址的第一个节点    }}void Hash::DeleteNode(ListNode *node){    ListNode *p = hashmap[hash_func(node->key)];    ListNode *q = NULL;    while(p)    {        if(p->key == node->key)//找到了        {            if(q) q->next = p->next;            else{               hashmap[hash_func(node->key)] = p->next;            }            delete p;            break;        }        else        {            q = p;            p = p->next;        }    }}

main.cpp

#include <iostream>#include "hash.h"#define HASHSIZE 100using namespace std;int main(){    Hash *h = new Hash();    ListNode* node1 = new ListNode(1,2);    ListNode* node2 = new ListNode(10,9);    ListNode* node3 = new ListNode(7,8);    ListNode* node4 = new ListNode(17,7);    h->InsertNode(node1);    h->InsertNode(node2);    h->InsertNode(node3);    h->InsertNode(node4);    int a = (*h)[7];    cout << a << endl;    delete node1,node2,node3,node4;    return 0;}
0 0