哈希表中的搜索功能

public class HashTable {


    /* Class containing next node and key and name value*/
    class Node { 
        private long key;

        public long getKey() {
            return key;
        }

        public void setKey(long key) {
            this.key = key;
        }

        private String value;

        public String getvalue() {
            return value;
        }

        public void setvalue(String value) {
            this.value = value;
        }

        Node next; 

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        Node(long key,String value) {
            this.key = key;
            this.value = value;
            next = null;
        }
    } 

我不确定是否应该像这样创建Node[] size

Node[] size;

    //The hash table array
    Node[] array = null;
    //hash table size. We typically choose m to be a power of 2
    int m = 0;

    // Constructor 
    HashTable(int size) {  
        m = size;
        array = new Node[size];  
    }

    HashTable() {  
        this(100);
    } 

    // Search for a given key in the hashtable
    // Note: you need to use hashFunction(long key) to determine the slot (array index) you will search in
    public Node search(long key) 
    { 
        Node node = null;
        /**
         * TODO
         */
        int hash = hashFunction(key);
        Node list = size[hash];
        while(list!=null) {
            if(list.getKey() == key) {
                return list;
            }
            else {
                list = list.getNext();
            }
        }
        return node;
    }

我的hashFunction(长键)可以工作,但是我无法实现搜索功能的逻辑。我不确定自己在做什么错。有人可以帮忙吗? 我对搜索的实现从public Node search(long key)开始。

p7888835 回答:哈希表中的搜索功能

您正在使用节点list = size[hash];在搜索中,但是正如我在参数构造函数中看到的那样,您正在使用array = new Node[size];对其进行初始化。

因此,尝试将size[hash]替换为array[hash]

在您粘贴的代码中,我还没有看到Node []size声明的任何使用。您可以删除size数组变量。

本文链接:https://www.f2er.com/3068086.html

大家都在问