Skip to content

Instantly share code, notes, and snippets.

@hacatu
Created December 3, 2015 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hacatu/4b228b58934bf762914c to your computer and use it in GitHub Desktop.
Save hacatu/4b228b58934bf762914c to your computer and use it in GitHub Desktop.
class LLNode {
String key, value;
int hashCode;
LLNode next;
LLNode(String k, String v, int h, LLNode n){
key = k; value = v;
hashCode = h;
next = n;
}
}
class Hashtable {
LLNode[] table;
int numValues;
float loadFactorThreshold;
Hashtable(float loadFactorThreshold){
table = new LLNode[10];
this.loadFactorThreshold = loadFactorThreshold;
}
public void insert(String key, String value){
int h = key.hashCode(), i = h%table.length;
if(i < 0)i += table.length;
table[i] = new LLNode(key, value, h, table[i]);
if((double)++numValues/table.length > loadFactorThreshold){
rehash();
}
}
public void rehash(){
LLNode[] tmp = new LLNode[table.length*2];
for(LLNode head : table){
while(head != null){
LLNode next = head.next;
int i = head.hashCode%tmp.length;
if(i < 0)i += tmp.length;
head.next = tmp[i];
tmp[i] = head;
head = next;
}
}
table = tmp;
}
}
public class e2p3 {
public static void main (String args[]) {
String[] values = {
"Winter",
"was",
"rudely",
"interrupted",
"by",
"a",
"cacophonous",
"buzzing",
"He",
"falling",
"the",
"continued",
"until",
"he",
"hit",
"offending",
"alarm",
"clock",
"with",
"respectable",
"gusto",
"Its"
};
Hashtable ht = new Hashtable(2.0f);
for(String value : values){
ht.insert(value, value);
}
for(LLNode head : ht.table){
while(head != null){
System.out.println(head.value);
head = head.next;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment