public class HashTabDemo {
public static void main(String[] args) {
HashTab h1 = new HashTab(5);
Emp emp1 = new Emp(0, "张三");
Emp emp2 = new Emp(1, "李四");
Emp emp3 = new Emp(2, "王二");
Emp emp4 = new Emp(3, "小明");
Emp emp5 = new Emp(4, "小红");
h1.add(emp1);
h1.add(emp2);
h1.add(emp3);
h1.add(emp4);
h1.add(emp5);
h1.findEmpOfId(1);
h1.list();
}
}
//创建HashTab
class HashTab {
private EmpLinkedList[] empLinkedListArray;
private int size;
public HashTab(int size) {
super();
this.size = size;
empLinkedListArray = new EmpLinkedList[size];
for (int i = 0; i < size; i++) {
empLinkedListArray[i] = new EmpLinkedList();
}
}
// 添加雇员
public void add(Emp emp) {
empLinkedListArray[hashFun(emp.id)].add(emp);
}
// 编写散列函数
public int hashFun(int id) {
return id % size;
}
// 遍历
public void list() {
for (int i = 0; i < size; i++) {
empLinkedListArray[i].list(i);
}
}
// 根据id查找雇员
public void findEmpOfId(int id) {
Emp emp;
EmpLinkedList empLinkedList = empLinkedListArray[hashFun(id)];
emp = empLinkedList.findEmpOfId(id);
if (emp == null) {
System.out.println("查无此人");
} else {
System.out.println(emp.toString());
}
}
}
class Emp {
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + "]";
}
public Emp() {
super();
}
}
class EmpLinkedList {
private Emp head;
public void add(Emp emp) {
if (head == null) {
head = emp;
return;
}
Emp curEmp = head;
while (true) {
if (curEmp.next == null) {
break;
}
curEmp = curEmp.next;
}
curEmp.next = emp;
}
// 遍历列表
public void list(int no) {
if (head == null) {
System.out.println("第" + no + "当前链表为空");
return;
}
System.out.print("第" + no + "链表信息为");
Emp curEmp = head;
while (true) {
System.out.println(curEmp.toString());
if (curEmp.next == null) {
break;
}
curEmp = curEmp.next;
}
}
// 查找
public Emp findEmpOfId(int id) {
if (head == null) {
return null;
}
Emp curEmp = head;
while (true) {
if (curEmp.id == id) {
break;
}
if (curEmp.next == null) {
curEmp = null;
break;
}
curEmp = curEmp.next;
}
return curEmp;
}
}
Java数据结构与算法(哈希表)
最新推荐文章于 2024-07-18 16:29:57 发布