简体   繁体   中英

HashTable using separate chaining

I'm trying to make a HashTable class using separate chaining. A problem exists that when I use the "insert" method like this:

public void insert(int k, int v) {
    if (k < 0 || k >= 10) {
        throw new IllegalArgumentException();
    }
    ListNode front = hTable.get(k);
    if (front.data == 0 && front.next == null) {
        front.data = v;
    } else { 
        front = new ListNode(v, front);
    }
}

my list ends up having only one node. Maybe because something happens when I insert the value at the front:

else { 
        front = new ListNode(v, front);
    }

But when I change this method and attempt to insert at the end of the list:

else {
        while (front.next != null) {
            front = front.next;
        }
        front.next = new ListNode(v);
    }

The list now works and could contain several values. Why I cannot insert at the front of the list?

front = new ListNode(v, front); changes the value of the local variable front, but not the value of hTable.get(k) . hTable.get(k) still returns the old value after changing front. To make this work, you also need to update hTable to store this new front as beginning of the chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM