链地址法:哈希表每个单元设置为链表,当关键字通过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();
}
}