数据结构: 哈希表

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();
    }
}
发布了605 篇原创文章 · 获赞 47 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/104446019