鏈地址法:哈希表每個單元設置爲鏈表,當關鍵字通過hashCode映射到哈希表單元中,將數據本身插入到該單元的鏈表中
數據結構層次:Info->Node->LinkList->HashTable
1、Node類
/*
* 鏈結點
*/
public class Node {
//數據域
public Info info; //員工信息
//指針域
public Node next;
//默認構造方法
public Node(Info info){
this.info=info;
}
}
2、LinkList類
/*
* 鏈表
*/
public class LinkList {
// 頭結點
private Node first;
public LinkList() {
first = null;
}
/*
* 插入一個結點,在頭結點後進行插入
*/
public void insertFirst(Info info) {
Node node = new Node(info);
if (first == null)
first = node;
else {
node.next = first;
first= node;
}
}
/*
* 刪除一個結點,在頭結點後進行刪除
*/
public Node deleteFirst() {
Node tmp = first;
first = tmp.next;
return tmp;
}
/*
* 查找,根據關鍵字
*/
public Node find(String key){
Node cur=first;
while(!key.equals(cur.info.getKey())){ //比較關鍵字
if(cur.next==null)
return null;
cur=cur.next;
}
return cur;
}
/*
* 刪除,根據關鍵字
*/
public Node delete(String key){
Node cur=first;
Node pre=first;
while(!key.equals(cur.info.getKey())){ //比較關鍵字
if(cur.next==null)
return null;
pre=cur;
cur=cur.next;
}
if(cur==first){ //刪第一個結點
first=first.next;
}
else{ //不是第一個結點
pre.next=cur.next;
}
return cur;
}
}
3、HashTable類
數組改成LinkList型
public class HashTable {
private LinkList[] arr;
/*
* 默認構造方法
*/
public HashTable(){
arr=new LinkList[100];
}
/*
* 數組初始化
*/
public HashTable(int maxSize){
arr=new LinkList[maxSize];
}
/*
* 插入數據
*/
public void insert(Info info){
//獲得關鍵字
String key=info.getKey();
//關鍵字對應的哈希數
int hashVal=hashCode(key);
//創建鏈表
if(arr[hashVal]==null){
arr[hashVal]=new LinkList();
}
//在鏈表中插入
arr[hashVal].insertFirst(info);
}
/*
* 查找數據
*/
public Info find(String key){
int hashVal=hashCode(key);
return arr[hashVal].find(key).info;
}
/*
* 刪除數據
*/
public Info delete(String key){
int hashVal=hashCode(key);
return arr[hashVal].delete(key).info;
}
/*
* 字母的ASCII碼求和/冪連乘
*/
public int hashCode(String key){
BigInteger hashValue=new BigInteger("0");
BigInteger pow27=new BigInteger("1");
for(int i=key.length()-1;i>=0;i--){
int letter=key.charAt(i)-96;
BigInteger letterB=new BigInteger(String.valueOf(letter));
hashValue=hashValue.add(letterB.multiply(pow27));
pow27=pow27.multiply(new BigInteger(String.valueOf(27)));
}
//壓縮可選值,但會出現衝突--->開放地址法、鏈地址法
return hashValue.mod(new BigInteger(String.valueOf(arr.length))).intValue();
}
}