第5章 散列——分离链接法

来源:互联网 发布:2016网络新词汇 编辑:程序博客网 时间:2024/06/02 18:09
#include <iostream>using namespace std;typedef int ElementType;struct ListNode{    ElementType elem;    ListNode* next;};struct HashTable{    int tableSize;    ListNode* *lists;};// 散列函数unsigned int Hash(ElementType key, int tableSize){    return key % tableSize;}// 散列表——初始化HashTable* InitializeTable(int tableSize){    HashTable* pHashTable;    // allocate table    pHashTable = (HashTable*)malloc(sizeof(struct HashTable));    if (pHashTable == NULL){        cout << "分配内存失败,Out of space!" << endl;    }    pHashTable->tableSize = tableSize; // NextPrime(tableSize);    // allocate array of lists    pHashTable->lists = (ListNode**)malloc(sizeof(struct ListNode));    if (pHashTable->lists == NULL){        cout << "分配内存失败,Out of space!" << endl;    }    // allocate list headers    for (int i = 0; i < pHashTable->tableSize; i++)    {        (pHashTable->lists)[i] = (ListNode*)malloc(sizeof(struct ListNode));        if ((pHashTable->lists)[i] == NULL){            cout << "分配内存失败,Out of space!" << endl;        }        else{            (pHashTable->lists)[i]->next = NULL;        }    }    return pHashTable;}// 散列表——查找ListNode* Find(HashTable hashTable, ElementType elem){    int index =  Hash(elem, hashTable.tableSize);// hash表(数组)中key(下标)    ListNode* list = hashTable.lists[index];     // 获取该index下的list    // 在list中寻找elem     while (list != NULL &&list->elem != elem)    {        list = list->next;    }    return list;}// 散列表——插入void Insert(HashTable hashTabel, ElementType elem){    ListNode *node, *newCell;    // index为散列表中key    int index = Hash(elem, hashTabel.tableSize);    ListNode* list = Find(hashTabel, elem);    if (list == NULL) //  要插入的elem不存在    {        newCell = (ListNode*)malloc(sizeof(ListNode));        if (newCell != NULL)// 链表插入操作        {            node = hashTabel.lists[index];            newCell->next = node->next;            newCell->elem = elem;            node->next = newCell;                   }    }}void main(){    HashTable* hashTable = InitializeTable(10);  //(HashTable*)malloc(sizeof(HashTable));    Insert(*hashTable, 0);    Insert(*hashTable, 1);    Insert(*hashTable, 4);    Insert(*hashTable, 9);    Insert(*hashTable, 16);    Insert(*hashTable, 25);    Insert(*hashTable, 36);    Insert(*hashTable, 49);    Insert(*hashTable, 64);    Insert(*hashTable, 81);    cout << Find(*hashTable, 0)->elem << endl;    cout << Find(*hashTable, 1)->elem << endl;    cout << Find(*hashTable, 4)->elem << endl;    cout << Find(*hashTable, 9)->elem << endl;    cout << Find(*hashTable, 16)->elem << endl;    cout << Find(*hashTable, 25)->elem << endl;    cout << Find(*hashTable, 36)->elem << endl;    cout << Find(*hashTable, 49)->elem << endl;    cout << Find(*hashTable, 64)->elem << endl;    cout << Find(*hashTable, 81)->elem << endl;    free(hashTable);    cin.get();}

参考:《数据结构与算法分析》——C语言描述 冯舜玺 译

0 0
原创粉丝点击