【韩顺平-数据结构】哈希表(学习笔记)

一、哈希表介绍

散列表(Hash table也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。

通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表

二、代码实现

package work.rexhao.hashtab;

/**
 * 哈希表
 */
public class HashTabDemo {
    public static void main(String[] args) {
        hashTab ht = new hashTab();
        ht.add(new stu(10,"wmh","123123"));
        ht.add(new stu(20,"wc","123123"));
        System.out.println(ht.find(10));
        System.out.println(ht.find(20));
        System.out.println(ht.find(30));
    }
}

/**
 * student的实体类
 */
class stu {
    private Integer no;
    private String name;
    private String phone;
    public stu next;

    stu(Integer no, String name, String phone) {
        this.no = no;
        this.name = name;
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "stu{" + "no=" + no + ", name='" + name + '\'' + ", phone='" + phone + '\'' + '}';
    }

    public Integer getNo() {
        return no;
    }


    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }

    public void setName(String name) {
        this.name = name;
    }


    public void setNo(Integer no) {
        this.no = no;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

/**
 * hashTab
 */
class hashTab {
    // 链表节点头部分
    stu[] head = new stu[10];

    /**
     * 添加节点的方法(尾插法) 将最后的next域指向新的node
     */
    public void add(stu s) {
        if (s == null) {
            return;
        }
        // 没有头指针,第一次添加需要直接放进head里面
        if(head[s.getNo() % 10] == null){
            head[s.getNo() % 10] = s;
            return;
        }
        // 需要一个辅助变量
        stu temp = head[s.getNo() % 10];
        // 遍历单链表
        while (temp.next != null) {
            temp = temp.next;
        }
        // 退出循环时,temp指向最后
        temp.next = s;
    }

    /**
     * 查找
     */
    public stu find(int no) {
        // 判空
        if (head[no % 10] == null) {
            return null;
        }
        // 遍历
        stu temp = head[no % 10];
        while (temp != null) {
            if (temp.getNo() == no) {
                break;
            }
            temp = temp.next;
        }
        return temp;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wmh1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值