So I am trying to implement a hashtable using an array of linklists. For practice I implemented my own linklist and now I am trying to implement the hash table. Now the hash function is very simple, it just takes the integer value of the char and mods it by the arraysize of the hasharray.
In the below code, I have commented the place where it errors out. It seems to hash the character value just fine, however when I try to insert it into the array of linklists, that's where it crashes.
I have tested the linklist class and that works fine. The error I get along with the system.out.println statements are:
Runtime error time: 0.07 memory: 380160 signal:-1
Created HashTable hashInsert hashFunction 2 hashFunctionAfter2f
Java Code: for class LinkListPractice
:
class LinkListPractice{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
HashTable testHashTable = new HashTable(10);
System.out.println("Created HashTable");
System.out.println(testHashTable.hashInsert('f'));
}
}
Java Code: for class HashTable
:
class HashTable{
LinkList[] hashArray;
int arraySize;
public HashTable(int size){
hashArray = new LinkList[size];
arraySize = size;
}
public int hashInsert(char value){
System.out.println("hashInsert");
int index = hashFunction(value);
System.out.println("hashFunctionAfter"+index+value);
/********************************************************
code gets to here but it fails after printing the above.
I think somehow the hashArray is not initialized
so it is failing trying to call the insertLink method
can someone tell me why it is failing here?
*********************************************************/
hashArray[index].insertLink(value);
return index;
}
public int hashFunction(char value){
System.out.println("hashFunction");
int index = (value % arraySize);
System.out.println(index);
return index;
}
}
Java Code: for class Link
:
class Link{
public char value;
public Link next;
public Link prev;
public Link(char data){
this.value = data;
this.next = null;
this.prev = null;
}
}
Java Code: for class LinkList
:
class LinkList{
public Link head;
public Link tail;
public LinkList(){
head = null;
tail = null;
}
public void insertLink(char data){
System.out.println("insertLink" + data);
Link newLink = new Link(data);
if (head == null && tail == null){
head = newLink;
tail = newLink;
}
else if (head == tail){
head.next = newLink;
newLink.prev = head;
tail = newLink;
}
else if (head != tail){
tail.next = newLink;
newLink.prev = tail;
tail = newLink;
}
}
public void printLinkList(){
Link currentLink = head;
while(currentLink != null){
System.out.println(currentLink.value);
currentLink = currentLink.next;
}
}
public void printLinkListPrev(){
Link currentLink = head;
while(currentLink != null){
if(currentLink.prev == null){
System.out.println("HEAD");
currentLink = currentLink.next;
}
else{
System.out.println(currentLink.prev.value);
currentLink = currentLink.next;
}
}
}
}