hash.h

来自「C++应用教程原码,里面包含该书中有十三章内容的代码,详细具体」· C头文件 代码 · 共 52 行

H
52
字号
template <class Type>
class hashTable {
    private:
         int numBuckets;  // 哈希表的长度
		 int divisor;     // 模值
         List<Type> * buckets; 
		 int hashFunction(const Type & k);
    public:
         hashTable(int num,int d) : numBuckets(num),divisor(d)
		 { buckets = new List<Type> [num];}		     
         void insert (const Type & k);
         void deleteNode (const Type & k);
         bool find (const Type & k);
		 Type *current;
};
/*
template <class Type>
Type hashTable <Type> ::hashFunction(const Type & k)
{
	return (k%divisor);
}
*/
template <class Type>
bool hashTable <Type> ::find(const Type & k)
{  int i = hashFunction(k);
   buckets[i].reset();
   if (buckets[i].size == 0)
  	  return false;
   else 
	 for (int j=0;j<buckets[i].size;j++)
	   { if (buckets[i].data() == k)  // 找到当前项,取出数值,并将当前指针指向它
	     { current = &(buckets[i].data());
	       return true;
		 }
		 buckets[i].next();
       }
    return false;
}

template <class Type>
void hashTable <Type> ::insert(const Type & k)
{  int i = hashFunction(k);
   buckets[i].insert(k);
}
template <class Type>
void hashTable <Type> ::deleteNode(const Type & k)
{  int i = hashFunction(k);
   if (find(k)) 
     buckets[i].deleteNode();
   else 
	 cout << "无法删除不存在的元素!"<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?