#include <stdio.h> #define M 100 #define Hash_key = 29 template <class T> struct HashNode { T data; int key; int isNull; HashNode<T>* pNext; HashNode(){ pNext = NULL; isNull = 1; } }; template <class T> class HashTable { private: HashNode<T> m_HashNodes[M]; int getHashAddress(int key) { return key % Hash_key; } public: HashTable(){ // for (i=0; i<M; i++) { // m_HashNodes[i].isNull = 0; // } } bool insert(int key,T data) { int address = this.getHashAddress(key); if (m_HashNodes[address].isNull == 1) { m_HashNodes[address].data = data; m_HashNodes[address].isNull == 0; } else { // while (m_HashNodes[address].isNull == 0 && address <M) { // 線性探測法, 開發地址法 // address++; // } // if (address == M) { // return false; // } // HashNode<T>* pTmpNode = m_HashNodes[address].pNext; // 鏈地址法 HashNode<T>* pCurNode = NULL while (pTmpNode != NULL) { pCurNode = pTmpNode; pTmpNode = pTmpNode->pNext; } pCurNode->pNext = new HashNode<T>(); pCurNode->pNext->data = data; pCurNode->pNext->key = key; pCurNode->pNext->isNull = 0; } } HashNode<T> find(int key) { int address = this.getHashAddress(key); HashNode<T> node = m_HashNodes[address]; if (node.key == key){ return &node.data; } else { pCur = m_HashNodes[address].pNext; while (pCur != NULL){ if (pCur->key == key) { return pCur; } else { pCur = pCur->pNext; } } return NULL } } }