数据结构: 哈希表

 

 

 

public class HashTabDemo {
    public static void main(String[] args) {
        Emp e1 = new Emp(1,"e1");
        Emp e2 = new Emp(2,"e2");
        Emp e3 = new Emp(3,"e3");
        Emp e4 = new Emp(4,"e4");
        Emp e5 = new Emp(5,"e5");

        HashTable hashTable = new HashTable(10);
        hashTable.add(e1);
        hashTable.add(e2);
        hashTable.add(e3);
        hashTable.add(e4);
        hashTable.add(e5);

        hashTable.list();
    }
}

class HashTable{
    private EmpLinkedList[] empLinkedListArray ;
    private int size; // 表示共有多少条链表

    // 构造器
    public HashTable(int size){
        this.size = size;
        empLinkedListArray = new EmpLinkedList[size];
        for (int i = 0; i < size; i++) {
            empLinkedListArray[i] = new EmpLinkedList();
        }
    }

    // 添加雇员
    public void add(Emp emp){
        // 根据员工的id得到该员工的应当添加到哪条链表
        int empLinkedListNo = hashFun(emp.id);
        empLinkedListArray[empLinkedListNo].add(emp);
    }

    // 遍历所有链表,遍历hashtab
    public void list(){
        for (int i = 0; i < size; i++) {
            System.out.printf("第%d个链表:",i);
            empLinkedListArray[i].list();
        }
    }

    // 编写一个散列函数,使用一个简单取模法
    public int hashFun(int id){
        return id%size;
    }
}

class Emp{
    public int id;
    public String name;
    public Emp next;

    public Emp(int id, String name){
        super();
        this.id = id;
        this.name = name;
    }
}

// 创建EmpLinkedList,表示链表
class EmpLinkedList{
    // 头指针, 执行第一个Emp,因此我们这个链表的head,
    //是直接指向第一个Emp
    private Emp head; // 默认为null

    // 添加雇员到链表
    public void add(Emp emp){
        // 如果是添加第一个雇员
        if(head == null){
            head = emp;
            return;
        }
        // 如果不是第一个雇员,即使用一个辅助的指针,帮助定位到最后
        Emp curEmp = head;
        while(true){
            if(curEmp.next == null){// 说明链表到最后
                break;
            }
            curEmp = curEmp.next;// 后移一位
        }

        curEmp.next = emp;
    }

    // 遍历链表的雇员信息
    public void list(){
        if(null == head){
            // 链表为空
            System.out.println("当前链表为空");
            return;
        }

        System.out.println("当前链表信息为:");
        Emp curEmp = head;
        while(null != curEmp){
            System.out.printf("=> id=%d name=%s\t",curEmp.id,curEmp.name);
            curEmp = curEmp.next; // 后移

        }
        System.out.println();
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值