散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
package com.wang;
import java.util.Scanner;
public class HashTable {
public static void main(String[] args) {
Hash hashT = new Hash(7);
//菜单
String key="";
Scanner sc=new Scanner(System.in);
while(true) {
System.out.println("a:添加员工");
System.out.println("l:显示员工");
System.out.println("f:查找员工");
System.out.println("d:删除员工");
System.out.println("e:退出系统");
key = sc.next();
switch (key) {
case "a":
System.out.print("id:");
int id = sc.nextInt();
System.out.print("名字:");
String name = sc.next();
Employee employee = new Employee(id, name);
hashT.add(employee);
break;
case "l":
hashT.list();
break;
case "f":
System.out.print("id:");
int id1 = sc.nextInt();
hashT.find(id1);
break;
case "d":
System.out.print("id:");
int id2 = sc.nextInt();
hashT.del(id2);
break;
case "e":
sc.close();
System.exit(0);
}
}
}
}
//创建Hash表,管理多条链表
class Hash{
private EmployeeList[] emplist;
//链表的数量
private int size;
//构造器
public Hash(int size) {
this.size = size;
emplist=new EmployeeList[size];
//初始化每一条链表!!!
for (int i = 0; i < size; i++) {
emplist[i] = new EmployeeList();
}
}
//添加
public void add(Employee e) {
//根据员工id添加到对应的链表中
int num=Hashfun(e.id);
emplist[num].add(e);
}
//编写散列函数,使用取模法
public int Hashfun(int id) {
return id%size;
}
//遍历所有的链表
public void list() {
for (int i = 0; i < size; i++) {
emplist[i].list(i);
}
}
//根据输入的ID查找雇员
public void find(int id) {
int num=Hashfun(id);
Employee emp=emplist[num].find(id);
if (emp != null) {
System.out.println("id:"+emp.id+"name:"+emp.name);
}else {
System.out.println("无");
}
}
//根据输入的ID删除雇员
public void del(int id) {
int num=Hashfun(id);
emplist[num].del(id);
}
}
//员工类
class Employee{
public int id;
public String name;
public Employee next;
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
//链表
class EmployeeList{
private Employee head;
//添加
public void add(Employee e) {
//添加第一个员工
if (head == null) {
head = e;
return;
}
//不是第一个员工,则定位到最后
Employee temp=head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = e;
}
//遍历
public void list(int no) {
if (head == null) {
System.out.println("第"+(no+1)+"条链表为空");
return;
}
Employee temp = head;
while(true) {
System.out.print("->id:"+temp.id+" name:"+temp.name);
if (temp.next == null) {
break;
}
temp = temp.next;
}
System.out.println();
}
//根据ID查找员工,找不到返回null
public Employee find(int id) {
if (head==null) {
System.out.println("链表为空");
return null;
}
Employee temp=head;
while (true) {
if (temp.id == id) {
break;
}
if (temp.next == null) {
temp=null;
break;
}
temp = temp.next;
}
return temp;
}
//根据ID删除员工,找不到返回null
public void del(int id) {
if (head==null) {
System.out.println("链表为空");
return;
}
Employee temp=head;
while (true) {
//如果要删除的是头节点
if (head.id == id) {
head = head.next;
return;
}
//如果要删除的是子节点
if (temp.next.id == id) {
temp.next=temp.next.next;
}
if (temp.next == null) {
break;
}
temp = temp.next;
}
}
}