// 建立一个哈希表
class HashTab {
private int size;
// 建立一个链表数组
EmpList[] empLists;
public HashTab(int size) {
this.size = size;
// 构建整个数组
empLists = new EmpList[size];
// 对数组中的链表进行初始化
for (int i = 0; i < size; i++) {
empLists[i] = new EmpList();
}
}
// 散列函数
public int hashMethod(int id) {
return id % size;
}
// 添加方法
public void add(Emp emp) {
// 通过散列函数返回的关键码值
int i = hashMethod(emp.getId());
empLists[i].add(emp);
}
// 删除方法
public void remove(int id) {
int i = hashMethod(id);
empLists[i].remove(id);
}
//修改
public void update(Emp emp){
int i = hashMethod(emp.getId());
empLists[i].update(emp);
}
// 遍历方法
public void list() {
for (int i = 0; i < size; i++) {
empLists[i].list(i);
}
}
}
// 新建一个hash的链表
class EmpList {
private Emp headEmp;
// 添加
public void add(Emp emp) {
if (headEmp == null) {
headEmp = emp;
return;
}
Emp temp = headEmp;
while (true) {
if (temp.getNext() == null) {
temp.setNext(emp);
break;
}
temp = temp.getNext();
}
}
// 删除
public void remove(int id) {
if (headEmp == null) {
System.out.println("链表为空,找不到需要删除的雇员");
return;
}
Emp temp = headEmp;
while (true) {
if (headEmp.getId() == id) {
headEmp = headEmp.getNext();
return;
}
if (temp.getNext() == null) {
break;
}
if (temp.getNext().getId() == id) {
temp.setNext(temp.getNext().getNext());
return;
} else {
System.out.println("找不到需要删除的雇员");
}
temp = temp.getNext();
}
}
// 修改
public void update(Emp emp) {
if (headEmp == null) {
System.out.println("该链表为空");
return;
}
Emp temp = headEmp;
while (true) {
if(temp.getId() ==emp.getId()){
temp.setName(emp.getName());
break;
}
if (temp.getNext() == null) {
break;
}
temp = temp.getNext();
}
}
// 遍历
public void list(int id) {
if (headEmp == null) {
System.out.println("第 " + (id + 1) + " 链表为空");
return;
}
Emp temp = headEmp;
System.out.print("第 " + (id + 1) + " 链表的雇员为");
while (true) {
// 如果不为空就会最少有一个值
System.out.print("-->" + temp.getId() + " " + temp.getName());
if (temp.getNext() == null) {
break;
}
temp = temp.getNext();
}
System.out.println();
}
}