哈希表基本功能实现
上篇👇
二叉搜索树的基本操作
哈希表头插法放入元素
/**
* user:ypc;
* date:2021-05-20;
* time: 11:05;
*/
public class HashBuck {
class Node {
public int key;
int value;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public int usedSize;
public Node[] array;
HashBuck() {
this.array = new Node[8];
this.usedSize = 0;
}
//JDk1.7及之前是头插法
public void put1(int key, int value) {
int index = key % this.array.length;
Node node = new Node(key, value);
Node cur = array[index];
while (cur != null) {
if (cur.key == key) {
cur.value = value;
return;
}
cur = cur.next;
}
node.next = array[index];
array[index] = node;
this.usedSize++;
if (loadFactor() > 0.75) {
resize1();
}
}
public double loadFactor() {
return this.usedSize / this.array.length * 1.0;
}
}
哈希表尾插法放入元素
//JDK1.8是尾插法
public Node findLast(Node head) {
if (head == null) return head;
Node cur = head;
while (cur.next != null) {
cur = cur.next;
}
return cur;
}
public void put2(int key, int value) {
int index = key % this.array.length;
Node node = new Node(key, value);
Node cur = array[index];
while (cur != null) {
if (cur.key == key) {
cur.value = value;
return;
}
cur = cur.next;
}
Node last = findLast(array[index]);
if (last == null) {
array[index] = node;
this.usedSize++