1.基本介绍
散列表,是根据关键码值(key—value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中的一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
实现方式:数组+链表;数组+二叉树
2.代码实现
//创建HashTab管理多条链表
class HashTab{
private EmpLinkedList[] empLinkedListArray;
private int size;//表示共有多少条链表
public HashTab(int size) {
this.size = size;
//初始化empLinkedListArray
empLinkedListArray = new EmpLinkedList[size];
//留一个坑?(**********不要忘记分别初始化每一条链表***********)
for (int i = 0;i < size;i++){
empLinkedListArray[i] = new EmpLinkedList();
}
}
//添加雇员
public void add(Emp emp){
//根据员工的id得到该员工应该加入到哪条链表
int empLinkedListNO = hashFun(emp.id);
//将emp添加到对应的链表中
empLinkedListArray[empLinkedListNO].add(emp);
}
//遍历哈希表
public void list(){
for (int i = 0 ;i < size;i++){
empLinkedListArray[i].list(i);
}
}
//根据输入的id查找雇员
public void findEmpById(int id){
//根据员工的id得到该员工在哪条链表
int empLinkedListNO = hashFun(id);
Emp emp = empLinkedListArray[empLinkedListNO].findEmpById(id);
if (emp!=null){//找到了
System.out.println("在第"+(empLinkedListNO+1)+"条链表中找到雇员"+id);
}else{
System.out.println("在哈希表中没找到该雇员");
}
}
//根据输入的id删除雇员
public void delById(int id){
int empLinkedListNO = hashFun(id);
empLinkedListArray[empLinkedListNO].delById(id);
}
//编写一个散列函数,使用简单的取模法来处理
public int hashFun(int id){
return id % size;
}
}
//创建EmpLinkedList,表示链表
class EmpLinkedList{
//头指针,指向第一个Emp,因此我们这个链表的head是有效的,直接指向第一个Emp
private Emp head;//默认为空
//添加雇员到链表
//假定添加雇员时id自增,即id总是从小到大,因此直接将id号加入到本链表的最后即可
public void add(Emp emp){
//添加第一个雇员
if (head == null){
head = emp;
return;
}
//如果不是第一个雇员,找到最后的结点
Emp cur = head;
while (true){
if (cur.next == null){
break;
}
cur = cur.next;
}
cur.next = emp;
}
//遍历链表的雇员信息
public void list(int no){
if (head == null){
System.out.println("第"+(no+1)+"链表为空");
return;
}
System.out.println("第"+(no+1)+"链表的信息为:");
Emp cur = head;
while (true){
System.out.println("id="+cur.id+" name="+cur.name);
if (cur.next == null){
break;
}
cur = cur.next;
}
System.out.println();
}
//根据id查找雇员
public Emp findEmpById(int id){
//判断链表是否为空
if (head == null){
System.out.println("链表为空");
return null;
}
Emp cur = head;
while (true){
if (cur.id == id){
break;//cur指向要查找的雇员
}
if (cur.next == null){
cur = null;
break;
}
cur = cur.next;
}
return cur;
}
//根据id删除雇员
public void delById(int id){
//判断链表是否为空
if (head == null){
System.out.println("链表为空,不能删除");
return;
}
Emp cur = head;
while (true){
if (head.id == id){//删除第一个节点
head = head.next;
break;
}
if (cur.next == null){
System.out.println("没找到要删除的数据");
break;
}
if (cur.next.id == id){
cur.next = cur.next.next;
break;
}
cur = cur.next;
}
}
}
//表示一个雇员
class Emp{
public int id;
public String name;
public Emp next;//默认为空
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}