哈希表
1、介绍
2、图示
3、思路分析
4、代码实现
package com.achang.hashtable;
public class HashTableDemo {
public static void main(String[] args) {
HashTable hashTable = new HashTable(3);
hashTable.add(new Emp(1,"阿昌1"));
hashTable.add(new Emp(2,"阿昌2"));
hashTable.list();
System.out.println("==========");
hashTable.findEmpById(3);
System.out.println("=================");
hashTable.deleteById(1);
System.out.println("=============");
hashTable.list();
}
}
class Emp {
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
this.name = name;
this.id = id;
}
}
class EmplinkedList {
public Emp head;
public void add(Emp emp) {
if (head == null) {
head = emp;
return;
}
Emp temp = head;
while (true){
if (temp.next == null){
break;
}
temp = temp.next;//后移,直到最后
}
temp.next = emp;
}
//删除
public void deleteById(int id){
Emp temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
System.out.println("已经到链表的最后");
break;
}
if (temp.next.id == id) {
System.out.println("找到了待删除的前一个节点");
flag = true;
}
temp = temp.next;
}
if (flag) {
temp.next = temp.next.next;
} else {
System.out.println("要删除的节点不存在");
}
}
//查找
public Emp findEmpById(int id){
if (head == null){
System.out.println("链表为空");
return null;
}
Emp temp = head;
while (true){
if (temp.id == id){
break;
}
if (temp.next == null){//没找到
temp = null;
break;
}
temp = temp.next;
}
return temp;
}
//遍历
public void list(){
if (head == null) {
System.out.println("链表为空");
return;
}
Emp temp = head;
while (true){
System.out.print(temp.id+temp.name+"--->");
if (temp.next ==null){
System.out.println();
break;
}
temp = temp.next;
}
}
}
class HashTable{
private EmplinkedList[] emplinkedLists;
private int size;
public HashTable(int size){
this.emplinkedLists = new EmplinkedList[size];
this.size = size;
//初始化每一条链表
for (int i = 0; i < this.emplinkedLists.length; i++) {
emplinkedLists[i] = new EmplinkedList();
}
}
public void deleteById(int id){
int index = id % size;
emplinkedLists[index].deleteById(id);
}
public void findEmpById(int id){
int index = id % size;
Emp emp = emplinkedLists[index].findEmpById(id);
if (emp != null){
System.out.println("找到了:"+emp.id+emp.name);
}else {
System.out.println("没有找到");
}
}
public void add(Emp emp){
//根据id添加
int index = emp.id % size;
emplinkedLists[index].add(emp);
}
public void list(){
for (EmplinkedList emplinkedList : emplinkedLists) {
emplinkedList.list();
}
}
}