Hash table
哈希表(Hash table)
- 又称散列表, 它是键值对数据结构, 也就是 key& value的映射集, 其中键是通过散列计算后, 将映射到表中某一个位置, 以此加快查找的速度. 此映射函数叫做散列函数, 存放值的数组叫做散列表
public class HashtableApp {
public static void main(String[] args) {
HashTab hashTab = new HashTab(3);
String key;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("add: 添加雇员");
System.out.println("list: 显示雇员");
System.out.println("find: 查找雇员");
System.out.println("exit: 退出系统");
key = scanner.next();
switch (key) {
case "add":
System.out.println("输入id");
int id = scanner.nextInt();
System.out.println("输入名字");
String name = scanner.next();
Emp emp = new Emp(id, name);
hashTab.add(emp);
break;
case "list":
hashTab.printAll();
break;
case "find":
System.out.println("请输入要查找的id");
id = scanner.nextInt();
hashTab.findEmpById(id);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}
}
}
/** 自定义 HashTab类*/
class HashTab {
private EmpLinkedList[] empLinkedListArr;
private int size;
public HashTab(int size) {
this.size = size;
empLinkedListArr = new EmpLinkedList[size];
for (int i = 0; i < size; i++) {
empLinkedListArr[i] = new EmpLinkedList();
}
}
public void add(Emp emp) {
int empLinkedListNo = hashFun(emp.id);
empLinkedListArr[empLinkedListNo].add(emp);
}
/** 遍历打印所有的链表*/
public void printAll() {
for (int i = 0; i < size; i++) {
empLinkedListArr[i].printAll(i);
}
}
/** 根据 id查找雇员*/
public void findEmpById(int id){
int empLinkedListIndex = hashFun(id);
Emp emp = empLinkedListArr[empLinkedListIndex].findById(id);
if(emp == null){
System.out.println("没有指定雇员!");
}else {
empLinkedListArr[empLinkedListIndex].printAll(id);
}
}
/** 散列函数*/
public int hashFun(int id){
return id % size;
}
}
/** 雇员类*/
class Emp {
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
", next=" + next +
'}';
}
}
/** 存放雇员的链表(不带头节点的链表)*/
class EmpLinkedList {
/** 指向第一个雇员*/
private Emp first;
/** 默认添加雇员信息到链表的最后节点*/
public void add(Emp emp) {
if(first == null) {
first = emp;
return;
}
Emp temp = first;
while (true) {
if(temp.next == null) {
break;
}
temp = temp.next;
}
temp.next= emp;
}
/** 遍历链表*/
public void printAll(int index) {
if(first == null) {
System.out.println("下标为" + index + "的链表为空!");
return;
}
System.out.println("下标为" + index + "的链表, 所有雇员!");
Emp temp = first;
while (true) {
System.out.println(" id:" + temp.id + ", name:" + temp.name);
if(temp.next == null) {
break;
}
temp = temp.next;
}
}
/** 根据 id查找雇员*/
public Emp findById(int no) {
if(first == null) {
System.out.println("当前链表为空!");
}
Emp temp = first;
while (true) {
/** 找到了*/
if(temp.id == no) {
break;
}
/** 到了链表的末尾*/
if(temp.next == null) {
temp = null;
break;
}
temp = temp.next;
}
return temp;
}
}
如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!