java实现hashTable
java实现hashTable
节点类
// 链表的节点
class Node {
public int id;
public String name;
public Node pre;
public Node next;
@Override
public String toString() {
return "Node{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public Node(int id, String name) {
this.id = id;
this.name = name;
}
链表类
// 链表
class NodeLinkedList {
// 头指针
private Node head;
// 添加到最后
public void add(Node node) {
// 第一次添加
if (head == null) {
head = node;
return;
}
Node temp = head;
while (true) {
if (temp.next == null) {
break;
}
// 右移
temp = temp.next;
}
temp.next = node;
}
// 遍历
public void show(int id) {
if (isEmpty()) {
System.out.printf("第%d条链表为空\n", id);
return;
}
Node temp = head;
while (true) {
System.out.println("第" + id + "条链表:" + temp);
if (temp.next == null) {
break;
}
temp = temp.next;
}
}
// 查找
public Node getNodeById(int id) {
if (isEmpty()) {
return null;
}
Node temp = head;
while (true) {
if (temp.id == id) {
return temp;
}
if (head.next == null) {
return null;
}
temp = temp.next;
}
}
// 辅助
private boolean isEmpty() {
return (this.head == null);
}
}
哈希表类
// 哈希表
class HashTable {
private NodeLinkedList[] nodeLinkedLists;
private int size;
public HashTable(int size) {
this.size = size;
this.nodeLinkedLists = new NodeLinkedList[size];
// 分别初始化每一个链表
for (int i = 0; i < size; i++) {
nodeLinkedLists[i] = new NodeLinkedList();
}
}
// 添加
public void add(Node node) {
// 根据id得到员工应该添加的链表
int hash = hash(node.id);
// 添加到链表中
this.nodeLinkedLists[hash].add(node);
}
// 遍历
public void show() {
for (int i = 0; i < nodeLinkedLists.length; i++) {
System.out.printf("第%d条链表\n", i);
nodeLinkedLists[i].show(i);
System.out.println("==============");
}
}
// 查找
public Node getNodeById(int id) {
int hash = hash(id);
Node node = nodeLinkedLists[hash].getNodeById(id);
return node;
}
// 散列函数,取模法
private int hash(int id) {
return id % this.size;
}
}
测试类
public class Demo {
public static void main(String[] args) {
HashTable hashTable = new HashTable(7);
String key = "";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("add :添加节点");
System.out.println("show:展示哈希表");
System.out.println("search:根据id查找");
System.out.println("exit:退出");
key = scanner.nextLine();
switch (key) {
case "add":
System.out.println("输入id");
int id = Integer.parseInt(scanner.nextLine());
System.out.println("输入姓名");
String name = scanner.nextLine();
Node node = new Node(id, name);
hashTable.add(node);
break;
case "show":
hashTable.show();
break;
case "search":
System.out.println("输入id:");
id = Integer.parseInt(scanner.nextLine());
Node byId = hashTable.getNodeById(id);
System.out.println(byId);
break;
case "exit":
scanner.close();
System.exit(0);
break;
default:
System.out.println("输入错了");
break;
}
}
}
}