Java数据结构与算法

Java数据结构:哈希表

2020-07-12  本文已影响0人  Patarw

1.基本介绍

2.实际题目

google公司的一个上机题:
有一个公司,当有新的员工来报道时,要求将该员工的信息加入(id,性别,年龄,名字,住址..),当输入该员工的id时,要求查找到该员工的所有信息.

由图可知我们需要创建三个类及其对应方法
1.HashTable类 (相当于图中蓝色部分)
2.EmpLinkedList类 (相当于图中绿色部分)
3.Emp类 (相当于图中黑色部分)

//Emp类
class Emp{
public int id;
public String name; 
public Emp next;
//构造方法
public Emp(int id, String name) {
    super();
    this.id = id;
    this.name = name;
}
@Override
public String toString() {  
    return "HeroNode [id=" + id + ", name=" + name +  "]";
}
 }


 // HashTable类
class HashTable{
 private EmpLinkedList[] emplist;
private int size;
public HashTable(int size) {
    this.size = size;
    emplist = new EmpLinkedList[size];
    for(int i = 0;i < emplist.length;i++) {
        emplist[i] = new EmpLinkedList();
    }
}   
public void list() {
    for(int i = 0;i < size;i++) {
        if(emplist[i].isEmpty()) {
            System.out.println("第"+i+"个节点链表为空");
        }else {
            System.out.println("第"+i+"个节点链表为:");
            emplist[i].list();
        }
    }
}   
public void findEmp(int id) {
    int index = 0;
    boolean flag = false;
    while(true) {
        if(emplist[index].findById(id) != null) {
            break;
        }
        if(index == emplist.length-1) {
            if(emplist[index].findById(id) == null) {
            flag = true;
            }
            break;
        }
        index++;
    }
    if(flag) {
        System.out.println("未找到该数据");
    }else {
        System.out.println("在第"+index+"个节点找到数据:"+emplist[index].findById(id));
    }
}   
public void add(Emp emp) {
    int tableIndex = hashFun(emp.id);
    emplist[tableIndex].add(emp);
}   
//编写散列函数
public int hashFun(int id) {
    return id % size;
}
}


//EmpLinkedList类
class EmpLinkedList{
private Emp head;   
public void add(Emp emp) {
    if(head == null) {
        head = emp;
        return;
    }
    Emp temp = head;
    while(true) {
        if(temp.next == null) {
            break;
        }
        temp = temp.next;
    }
    temp.next = emp;
}   
public boolean isEmpty() {
    if(head == null) {
        return true;
    }else {
        return false;
    }
}   
public void list() {
    if(isEmpty()) {
        System.out.println("链表为空");
    }
    Emp temp = head;
    while(true) {           
        System.out.println(temp.toString());
        if(temp.next == null) {
            break;
        }
        temp = temp.next;
    }       
}
public Emp findById(int id) {
    if(isEmpty()) {
        return null;
    }
    Emp temp = head;
    while(true) {
        if(temp.id == id) {
            return temp;
        }
        if(temp.next == null) {
            return null;
        }
        temp = temp.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读