散列
之前写好的都发表了,不知道为啥被覆盖了,心痛到无法呼吸o(╥﹏╥)o,这里就不写什么基本的散列函数、散列函数的选择啊,散列过程图了,以后有时间有心情再补吧,直接贴个实现代码好了…….
public class SeparateChainingHashTable <T>{
private static final int DEFAULT_TABLE_SIZE = 10;//默认容量,数组中链表的个数
private List<T>[] TheLists;//链表数组
private int current_size;//当前数据个数
public SeparateChainingHashTable(int size) {
TheLists = new LinkedList[nextPrime(size)];
for(int i = 0; i < TheLists.length; i++) {
TheLists[i] = new LinkedList<>();
}
}
public SeparateChainingHashTable() {
this(DEFAULT_TABLE_SIZE);
}
//置表空
public void MakeEmpty() {
for (List<T> list : TheLists) {
list.clear();
}
current_size = 0;
}
/**
* 哈希表是否包含某元素
* @param x 查询元素
* @return 查询结果
*/
public boolean contains(T x) {
List<T> whichList = TheLists[MyHash(x)];
return whichList.contains(x);
}
/**
* 哈希算法,有多种实现方法
* @param x 元素
* @return 哈希值
*/
private int MyHash(T x) {
int tmp = x.hashCode();
tmp %= TheLists.length;
if (tmp < 0) {
tmp += TheLists.length;
}
return tmp;
}
/**
* 向哈希表中插入某元素,若存在则不操作
* @param x 插入元素
*/
public void insert(T x) {
List<T> whichList = TheLists[MyHash(x)];
if (!whichList.contains(x)) {
whichList.add(x);
if (++current_size > TheLists.length) {
ReHash();
}
}
}
/**
* 再散列函数,插入空间不够时执行
*/
private void ReHash() {
List<T>[] oldLists = TheLists;
// 分配一个两倍大小的空表
TheLists = new List[nextPrime(2 * TheLists.length)];
for(int j=0;j<TheLists.length;j++){
TheLists[j]=new LinkedList<T>();
}
current_size = 0;
for (int i = 0; i < oldLists.length; i++) {
for (T item : oldLists[i]) {
insert(item);
}
}
}
/**
* 向哈希表中删除某元素,若不存在则不操作
* @param x 删除元素
*/
public void remove(T x) {
List<T> whichList = TheLists[MyHash(x)];
if (whichList.contains(x)) {
whichList.remove(x);
current_size--;
}
}
/**
* 返回不小于某个整数的素数
* @param num 整数
* @return 下一个素数(可以相等)
*/
private static int nextPrime(int num) {
if (num == 0 || num == 1 || num == 2) {
return 2;
}
if (num % 2 == 0) {
num++;
}
while (!isPrime(num)) {
num += 2;
}
return num;
}
/**
* 检查某整数是否为素数
* @param num 检查整数
* @return 检查结果
*/
private static boolean isPrime(int num) {
if (num == 2 || num == 3) {
return true;
}
if (num == 1 || num % 2 == 0) {
return false;
}
for (int i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
/**
* 输出散列表
*/
public void printTable() {
for(int i=0;i<TheLists.length;i++){
System.out.println("-----");
Iterator iterator=TheLists[i].iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
}
}
}