今天太累了,不想写原理了,简单记一下供以后复习 简单的讲就是通过散列函数求出待插入/查找元素的位置,然后将其插入到那个位置的链表即实现,这里散列函数用的取模法
创建Person类,用作存储数据
class Person {
public int id
;
public String name
;
public Person next
;
public Person(int id
, String name
) {
this.id
= id
;
this.name
= name
;
}
}
创建链表类
class PersonLinkedList {
private Person head
;
public void add(Person person
){
if (head
==null
){
head
= person
;
return;
}
Person temp
= head
;
while (true){
if (temp
.next
== null
){
break;
}
temp
= temp
.next
;
}
temp
.next
= person
;
}
public void print(int num
){
if (head
==null
){
System
.out
.println("链表"+(num
+1)+"为空");
return;
}
Person temp
=head
;
while (true){
if (temp
== null
){
break;
}
System
.out
.println("链表"+(num
+1)+"的信息为==> id=>"+temp
.id
+":"+"name=>"+temp
.name
);
temp
=temp
.next
;
}
System
.out
.println();
}
public Person
findByid(int id
){
if (head
==null
){
System
.out
.println("链表为空");
return null
;
}
Person temp
= head
;
while (true){
if (temp
.id
==id
){
break;
}
if (temp
.next
==null
){
temp
=null
;
break;
}
temp
=temp
.next
;
}
return temp
;
}
}
创建HashTable类
class HashTable {
private int size
;
private PersonLinkedList
[] personLinkedLists
;
public HashTable(int size
) {
this.size
=size
;
personLinkedLists
=new PersonLinkedList[size
];
for (int i
=0;i
<size
;i
++){
personLinkedLists
[i
]=new PersonLinkedList();
}
}
public void add(Person person
){
int personLinkedListNo
= sanlie(person
.id
);
personLinkedLists
[personLinkedListNo
].add(person
);
}
public void list(){
for (int i
= 0;i
< size
; i
++){
personLinkedLists
[i
].print(i
);
}
}
public void findById(int id
){
int listNo
= sanlie(id
);
Person person
= personLinkedLists
[listNo
].findByid(id
);
if (person
!=null
){
System
.out
.println("在第"+(listNo
+1)+"个链表找到:"+"id:"+person
.id
+"name:"+person
.name
);
}else {
System
.out
.println("未找到目标");
}
}
public int sanlie(int id
){
return id
% this.size
;
}
}
转载请注明原文地址: https://mac.8miu.com/read-513436.html