bancqm
bancqm

Reputation: 101

Linked List in my Array not working

I am trying to create a program to store words in a Array. I have a hashFunction which computes a Integer value. This value is used to put the Word in a Node if that position in the array is null. If there is already a Cell there, it should create a new Cell with the word as its data type, and it should then point to the old Cell with all the other data. However this dosen't seem to be working - I have added a few words and although it adds the first word to the Cell the other words aren't being added. I'm not sure why this is happening - can someone show my why?

public class test2{

    public static class Node<T>{
        public T data;
        public Node<T> next;

    public Node(T data, Node<T> next)
    {
       this.data = data;
       this.next = next;
    }
 }



    static Node[] array = new Node[10]; 

    public static void add(String word){
        int position = hashFunction(word);
        if(array[position] == null){
            array[position] = new Node(word, null);
        }else{
            new Node(word, array[position]);
        }
    }

    public static int hashFunction(String a){
        int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
        }
     return sum % array.length;
 }

 public static void main(String[] args) {
     add("abc");
     add("acb");
     add("bca");
     add("bac");
     add("cba");
     System.out.println(array[4].next);
 }
}

Upvotes: 0

Views: 56

Answers (2)

Jules Dupont
Jules Dupont

Reputation: 7567

You're adding the word as a new node in your linked list, but you're never storing a reference to the new node. When you add a node at the beginning of a linked list, you have to store the new node as the new head of the list.

In your case, you could accomplish that with the following:

public static void add(String word){
    int position = hashFunction(word);
    if(array[position] == null){
        array[position] = new Node(word, null);
    }else{
        Node newHead = new Node(word, array[position]);
        array[position] = newHead;
    }
}

Now your linked list will have all of the words you're expecting. You could also iterate over the linked list in array[position] and add the new node at the end of the list if that's more appropriate for your use case.

Upvotes: 2

Lo&#239;c
Lo&#239;c

Reputation: 591

Instead of

new Node(word, array[position])

You should do the following:

array[position] = new Node(word, array[position]);

With the original line of code you are correctly creating an new instance of Node to which you assigned the current array[position] as its next value.

But array[position] is still the same, you need to change it to the newly created instance of Node.

Upvotes: 3

Related Questions