哈希(散列)的分离链接法

2018-02-27 11:54:02来源:oschina作者:算法之名人点击

分享
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.LinkedList;
/**
* Created by Administrator on 2018-02-21.
*/
public class SeparateChainingHashTable {
private static final int DEFAULT_TABLE_SIZE = 10;
private List[] theLists;
private int currentSize;
public SeparateChainingHashTable() {
this(DEFAULT_TABLE_SIZE);
}
public SeparateChainingHashTable(int size) {
theLists = new LinkedList[nextPrime(size)];
for (int i = 0;i < theLists.length;i++) {
theLists[i] = new LinkedList<>();
}
}
private int myhash(AnyType x) {
int hashVal = x.hashCode();
hashVal %= theLists.length;
if (hashVal < 0) {
hashVal += theLists.length;
}
return hashVal;
}
public void insert(AnyType x) {
List whichList = theLists[myhash(x)];
if (!whichList.contains(x)) {
whichList.add(x);
if (++currentSize > theLists.length)
rehash();
}
}
public void remove(AnyType x) {
List whichList = theLists[myhash(x)];
if (whichList.contains(x)) {
whichList.remove(x);
currentSize--;
}
}
public boolean contains(AnyType x) {
List whichList = theLists[myhash(x)];
return whichList.contains(x);
}
public void makeEmpty() {
for (int i = 0;i < theLists.length;i++) {
theLists[i].clear();
}
currentSize = 0;
}
private void rehash() {
List[] oldLists = theLists;
theLists = new List[nextPrime(2 * theLists.length)];
for(int j = 0;j < theLists.length;j++){
theLists[j] = new LinkedList();
}
currentSize = 0;
for (int i = 0; i < oldLists.length; i++) {
for (AnyType item : oldLists[i]) {
insert(item);
}
}
}
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;
}
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();
}
}
public static void main(String[] args) {
Random random = new Random();
SeparateChainingHashTable hashTable = new SeparateChainingHashTable();
for (int i = 0; i < 30; i++) {
hashTable.insert(random.nextInt(30));
}
hashTable.printTable();
}
}

把散列到相同值的数放入到双向链表中保存。

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台