Skip to content

Instantly share code, notes, and snippets.

@rootid
Created June 6, 2015 20:18
Show Gist options
  • Save rootid/0a287e19afeb63d8f9a3 to your computer and use it in GitHub Desktop.
Save rootid/0a287e19afeb63d8f9a3 to your computer and use it in GitHub Desktop.
class HashTable {
class Entry {
//private final String key; Deleting the Entry ?
private String key;
private String value;
private Entry next;
Entry (String key,String value) {
this.key = key;
this.value = value;
this.next = null;
}
}
private Entry tableInstance[];
private static final int SIZE = 100;
HashTable () {
tableInstance = new Entry[SIZE];
}
private int getHash (String key) {
int hash_value = 31;
for (int i=0;i < key.length();i++) {
hash_value += 13 * key.charAt(i) ;
}
return hash_value % SIZE;
}
public void put(String key,String value) {
int hVal = getHash(key);
boolean isKeyFound = false;
if (tableInstance[hVal] == null) {
tableInstance[hVal] = new Entry(key,value);
} else {
Entry e = tableInstance[hVal];
while (e.next != null) {
if (e.key == key) {
e.value = value;
isKeyFound = true;
break;
}
e = e.next;
}
if (false == isKeyFound) {
Entry head = tableInstance[hVal];
Entry newHead = new Entry(key,value);
newHead.next = head;
head = newHead;
}
}
}
public String get(String key) {
int hVal = getHash(key);
Entry e = tableInstance[hVal];
while (e.next != null) {
if (e.key == key) {
return e.value;
}
e = e.next;
}
return null;
}
public bool delete(String key) {
int hVal = getHash(key);
Entry e = tableInstance[hVal];
if (e.next == null) {
e = null;
return true;
}
while (e.next != null) {
if (e.key == key) {
e.key = e.next.key;
e.value = e.next.value;
e = e.next.next;
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment