哈希表存电话号码的实现(Java)

哈希表存电话号码的实现(Java),第1张

哈希+单链表

核心code:
//哈希表存人员电话
public class hashtabdemo {
    public static void main(String[] args) {
        hash hash = new hash(5);
        data peo = new data(32 , 138387);
        hash.add(peo);
        hash.read(32);
    }
}
class data{
    public int id;
    public int phone;
    public data next = null;
    public data(int id, int phone) {
        this.id = id;
        this.phone = phone;
    }
}
class hash{
    private data[] hash ;
    int size;
    public hash(int size) {
        hash = new data[size];
        this.size=size;
        for (int i = 0; i < size; i++) {
            hash[i] = new data(0,0);
        }
    }

    public int location(int a){
        return a % size;
    }

    public void add(data pp){
        int loc = location(pp.id);
        if(hash[loc].next == null){
            hash[loc].next = pp;
            return;
        }
        data temp = hash[loc];
        while (temp.next != null) temp = temp.next;
        temp.next = pp;
        return;
    }

    public void read(int dd){
        data temp = hash[location(dd)];
        while (temp != null){
            if (temp.id == dd){
                System.out.println(temp.phone);
                return;
            }
            temp = temp.next;
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/733828.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存