增删改查操作需要在链表里写一个方法再在哈希表中写出,最后测试,第一次写仅实现增查功能,在输出方面有瑕疵。
import java.util.Scanner;
public class HashTabDemo {
public static void main(String[] args) {
HashTab hashTab = new HashTab(10);
String key = "";
boolean loop = true;
Scanner sc = new Scanner(System.in);
while (loop) {
System.out.println("add:");
System.out.println("list:");
System.out.println("find:");
System.out.println("exit:");
key = sc.next();
switch (key) {
case "add":
System.out.println("输入id");
int id = sc.nextInt();
System.out.println("输入名字");
String name = sc.next();
Stu stu = new Stu(id, name);
hashTab.add(stu);
break;
case "list":
hashTab.list();
break;
case "find":
System.out.println("请输入查找的id");
int res = sc.nextInt();
hashTab.findStuByID(res);
break;
case "exit":
sc.close();
loop = false;
break;
default:
break;
}
}
}
}
class HashTab {
private StuLinkedList[] StuLinkedListArray;
private int size;
// 构造器
public HashTab(int size) {
this.size = size;
StuLinkedListArray = new StuLinkedList[size];
// 分别初始化每一条链表
for (int i = 0; i < size; i++) {
StuLinkedListArray[i] = new StuLinkedList();
}
}
public void add(Stu stu) {
// 根据学生的身份得知他应该添加到哪条链表
int StuLinkedListNO = hashFun(stu.id);
StuLinkedListArray[StuLinkedListNO].add(stu);
}
// 遍历整个哈希表
public void list() {
for (int i = 0; i < size; i++) {
StuLinkedListArray[i].list(i);
}
}
// 编写散列函数
public int hashFun(int id) {
return id % size;
}
// 根据输入的id查找雇员
public void findStuByID(int id) {
int StuLinkedListNO = hashFun(id);
Stu stu = StuLinkedListArray[StuLinkedListNO].findStuByID(id);
if (stu != null) {
System.out.printf("在第%d条链表中找到雇员 id=%d\n", StuLinkedListNO, id);
}
}
}
class StuLinkedList {
// 这个链表的head是直接指向第一个学生Stu
private Stu head;//
public void add(Stu stu) {
if (head == null) {
head = stu;
return;
}
Stu temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = stu;
}
public void list(int no) {
if (head == null) {
System.out.println("第 " + no + " 条链表为空");
return;
}
System.out.print("第 " + no + " 条链表的信息为:");
Stu temp = head;
while (true) {
System.out.printf("id=%d name=%s\t", temp.id, temp.name);
if (temp.next == null) {
break;
}
temp = temp.next;
}
System.out.println();
}
// 根据id查找学生
public Stu findStuByID(int id) {
if (head == null) {
System.out.println("链表为空");
return null;
}
Stu temp = head;
while (true) {
if (temp.id == id) {
break;
}
if (temp.next == null) {
temp = null;
break;
}
temp = temp.next;
}
return temp;
}
}
//表示一个学生
class Stu {
public int id;
public String name;
public Stu next;
public Stu(int id, String name) {
super();
this.id = id;
this.name = name;
}
}