Java哈希表的实现

文章目录


实现代码

class EmpNode{
    public int id;
    public String name;
    public EmpNode pNext;//默认为null
    //构造器
    public EmpNode(int id, String name){
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "EmpNode{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

class EmpList{
    //头指针,指向第一个雇员
    private EmpNode head;//默认为空

    //成员方法

    //插入,直接插入到链表最后
    public void add(EmpNode newNode){
        //如果链表为空
        if(null == head){
            head = newNode;
            return;
        }
        //链表不为空
        else{
            EmpNode cur = head;
            while(null != cur.pNext){
                cur = cur.pNext;
            }
            cur.pNext = newNode;
        }
    }

    //遍历
    public void traverse(int no){
        if(null == head){
            System.out.println(no + "号链表为空!");
        }
        else{
            //链表不为空
            System.out.println(no + "号链表的信息为:");
            EmpNode cur = head;
            while(null != cur){
                System.out.println(cur);
                cur = cur.pNext;
            }
            System.out.println("当前链表遍历完毕!");
        }
    }
    //查找
    public void findById(int id){
        if(null == head){
            System.out.println("链表为空,查找失败");
            return;
        }
        EmpNode cur = head;
        while(null != cur){
            if(cur.id == id){
                System.out.println("找到了,员工信息为:"+cur);
                return;
            }
            cur = cur.pNext;
        }
        System.out.println("该员工不存在");
    }
}

class HashTab{
    private EmpList[] empListArray;
    private int size;//共有多少条链表

    //构造器
    public HashTab(int size){
        this.empListArray = new EmpList[size];
        for(int i = 0; i < size; i ++){
            empListArray[i] = new EmpList();
        }
        this.size = size;
    }

    //散列函数
    public int hashFun(int id){
        return id % size;
    }
    //插入
    public void add(EmpNode newNode){
        //根据员工id添加
        empListArray[hashFun(newNode.id)].add(newNode);
    }
    //遍历
    public void traverse(){
        for(int i = 0; i < size; i++) {
            empListArray[i].traverse(i);
        }
    }
    //查找
    public void findById(int id){
        empListArray[hashFun(id)].findById(id);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值