Java数据结构温习之哈希表-链地址法

哈希表分为两大类,一是开放地址法,二是链地址法。
1)、开放地址法中,通过在哈希表中再找一个空位解决冲突问题。
2)、链地址法中,某个数据项的关键字值还是像通常一样映射到哈希表的单元,而数据项本身插入到这个单元的链表中,其他同样映射到该位置的数据项只需要加入到链表中。

链地址法Java简缩代码:

/**
* 节点类
*/
class Link{
private int data;
public Link next;

public Link(int data){
this.data = data;
this.next = null;
}

public int getKey(){
return this.data;
}

public void display(){
System.out.println(this.data);
}
}

/**
* 优先级链表
*/
class SortedList{
private Link first;

public SortedList(){
this.first = null;
}

public void insert(Link theLink){
int key = theLink.getKey();
Link current = this.first;
Link previous = null;

while (current != null && key > current.getKey()){
previous = current;
current = current.next;
}

if (previous != null){
previous.next = theLink;
}else{
this.first = theLink;
}

theLink.next = current;
}

public Link find(int key){
Link current = this.first;
while (current != null && key != current.getKey()){
current = current.next;
}

return current;
}

public void display(){
Link current = this.first;
while (current != null){
current.display();
current = current.next;
}
}
}

/**
* 链地址哈希表
*/
class HashTableLink{
private SortedList[] hashArray;
private int arraySize;

public HashTableLink(int size){
this.arraySize = size;
this.hashArray = new SortedList[this.arraySize];
for (int i = 0; i < this.arraySize; i++){
this.hashArray[i] = new SortedList();
}
}

public int keyFunc(int key){
return key % this.arraySize;
}

public void insert(Link theLink){
int key = keyFunc(theLink.getKey());
this.hashArray[key].insert(theLink);
}

public Link find(int key){
key = keyFunc(key);
return this.hashArray[key].find(key);
}

public void display(){
for (int i = 0; i < this.arraySize; i++){
System.out.println("i: " + i);
this.hashArray[i].display();
}
}

}

public class HashTableTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashTableLink htl = new HashTableLink(3);
for (int i = 1; i < 12; i ++){
Link link = new Link(i);
htl.insert(link);
}

htl.display();

}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值