Skip to content

Instantly share code, notes, and snippets.

@ninjachen
Created September 15, 2024 14:31
Show Gist options
  • Save ninjachen/fc163ab34b5e6b9634f86f8e37377939 to your computer and use it in GitHub Desktop.
Save ninjachen/fc163ab34b5e6b9634f86f8e37377939 to your computer and use it in GitHub Desktop.
hand write hashmap
class MyHashMap {
static class Node {
public int key;
public int value;
public Node prev;
public Node next;
}
static Node first;
static Node last;
public MyHashMap() {
}
public void put(int key, int value) {
Node n = new Node();
n.key = key;
n.value = value;
if (first == null) {
first = n;
last = n;
} else {
Node tmp = first;
for (; tmp != null; tmp = tmp.next) {
if (tmp.key == key) {
tmp.value = value;
return;
}
}
// append to last
last.next = n;
// System.out.println(String.format("%v/%v/%v", first, n, last));
n.prev = last;
last = n;
}
}
public int get(int key) {
if (first == null) {
return -1;
}
Node n = first;
for (; n != null; n = n.next) {
// System.out.println(String.format("n %d/%d, target key is %d", n.key, n.value,
// key));
if (n.key == key) {
// System.out.println(String.format("found n %d/%d, target key is %d", n.key,
// n.value, key));
return n.value;
}
}
return -1;
}
public void remove(int key) {
Node n = first;
for (; n != null; n = n.next) {
if (n.key == key) {
n.prev.next = n.next;
return;
}
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment