⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 a_13_3.cpp

📁 C++应用教程原码,里面包含该书中有十三章内容的代码,详细具体
💻 CPP
字号:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <string>
#include "List.h"
using namespace std;

template <class Type>
class hashTable {
    private:
         int numBuckets;  // 哈希表的长度
		 int divisor;     // 模值
         List<Type> * buckets; 
		 Type 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);
};

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)
	       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;
}

void main()
{ 
  hashTable <int> a(10,11);
  a.insert(45);
  a.insert(80);
  a.insert(89);
  a.insert(100);
  if (a.find(100)) cout << "找到100啦!"<<endl;
  if (a.find(111)) cout << "找到111啦!"<<endl;
  a.deleteNode(89);
  if (!a.find(89)) cout << "找不到89啦!"<<endl; 
  a.deleteNode(80);
  if (!a.find(80)) cout << "找不到80啦!"<<endl; 
  cin.get(); //等待结束,以便调测程序,可以删除
}

⌨️ 快捷键说明

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