The goal of this program is to create a hash table where every integer inserted is mapped to that number % 10 position within an array. For some reason, I am creating the same linked list for each index of the table. For example, the final output is currently:
0: 28 15 8 18 25
1: 28 15 8 18 25
2: 28 15 8 18 25
etc
When it should be:
0: Empty.
1: Empty.
2: Empty.
3: Empty.
4: Empty.
5: 15 25
6: Empty.
7: Empty.
8: 28 8 18
9: Empty.
Here is my code with each class separated by slashes:
public class myHash{
public static LinkedList[] array = new LinkedList[10];
public static int hash(int value){
return value % 10;
}
public static void initArray(){
for(int i = 0; i < 10; i++){
array[i] = new LinkedList();
}
}
public static void insert(int value){
int index = hash(value);
System.out.println("Inserting " + value + " at location " + index + ".");
LinkedList list = array[index];
list.insertData(value);
array[index] = list;
}
public static void delete(int value){
int index = hash(value);
LinkedList list = array[index];
list.remove(value);
}
public static void dumphash(){
for(int i = 0; i < 10; i++){
LinkedList list = array[i];
System.out.println(i + ":" + list.dumplist());
}
}
public static void main(String args[]){
initArray();
insert(1);
insert(5);
insert(28);
delete(5);
insert(15);
insert(8);
dumphash();
delete(1);
insert(18);
insert(25);
delete(33);
dumphash();
}
}
////////////////////////////
public class LinkedList{
static Node head;
public LinkedList() {
head = null;
}
public void insertData(int data){
Node node = new Node();
node.data = data;
node.next = null;
if(head == null){
head = node;
}
else{
Node n = head;
while(n.next != null){
n = n.next;
}
n.next = node;
node.setValue(data);
}
}
public static void remove(int data){
Node node = head;
boolean removed = false;
if(node.getValue() == data){
Node temp = head;
head = head.next;
temp.next = null;
System.out.println(data + " has been removed.");
removed = true;
}
else{
while(node.next != null){
if(node.next.getValue() == data){
node.next = node.next.next;
System.out.println(data + " has been removed.");
removed = true;
}
else{
node = node.next;
if(node.next == null && removed == false){
System.out.println("Error: " + data + " has not been inserted.");
}
}
}
}
}
public static String dumplist(){
String fullList = "";
Node node = head;
if(node.getValue() == null){
fullList = " Empty.";
}
else{
while(node.next != null){
fullList = fullList + " " + node.data;
node = node.next;
}
fullList = fullList + " " + node.data;
}
return fullList;
}
}
////////////////////////////
public class Node{
int data;
Node next;
public Integer getValue(){
return data;
}
public void setValue(int val){
this.data = val;
}
}
Any help would be greatly appreciated!