8-哈希表-Scala实现

liqinglin0 2020-07-05

哈希表又叫散列表,这里用数组和链表实现

package com.atguigu.datastructures.hashtable
import scala.util.control.Breaks._
object HashTableDemo {
  def main(args: Array[String]): Unit = {
    val hashTable = new HashTable(5)
    val emp1 = new Emp(5,"aa")
    val emp2 = new Emp(11,"bb")
    val emp3 = new Emp(15,"cc")
    val emp4 = new Emp(20,"dd")
    val emp5 = new Emp(6,"ee")
    val emp6 = new Emp(11,"ff")
    val emp7 = new Emp(7,"gg")
    val emp8 = new Emp(8,"hh")
    val emp9 = new Emp(24,"jj")
    hashTable.addEmp(emp1)
    hashTable.addEmp(emp2)
    hashTable.addEmp(emp3)
    hashTable.addEmp(emp4)
    hashTable.addEmp(emp5)
    hashTable.addEmp(emp6)
    hashTable.addEmp(emp7)
    hashTable.addEmp(emp8)
    hashTable.addEmp(emp9)
    hashTable.list()
    hashTable.findEmpById(100)
  }
}
//编写hashtable
class HashTable(size:Int){
  //一个EmpLinkedList数组
  val empLinkedListArr = new Array[EmpLinkedList](size)
  for (i <- 0 until size){
    empLinkedListArr(i)=new EmpLinkedList()
  }
  //添加
  def addEmp(emp: Emp): Unit ={
    val empLinkedListNo = hash(emp.no)
    empLinkedListArr(empLinkedListNo).addEmp(emp)
  }
  //遍历hashtable
  def list(): Unit ={
    for (i <- 0 until size){
      empLinkedListArr(i).list(i)
    }
  }
  //编写一个hash方法(散列函数)
  def hash(no:Int): Int ={
    no % size
  }
  def findEmpById(no:Int): Unit ={
    //先计算该no对应的链表
    val empLinkedListNo = hash(no)
    val emp = empLinkedListArr(empLinkedListNo).findEmpByNo(no)
    println()
    if (emp!=null){
      printf("找到 no=%d name = %s",no,emp.name)
    }else{
      printf("没有找到该雇员="+no)
    }
  }
}
//Emp类
class Emp(empNo:Int,eName:String){
  val no = empNo
  var name = eName
  var next:Emp = null
}

//编写Emplinkedlist,存放的是雇员信息
class EmpLinkedList{
  var head:Emp = null

  //查询雇员
  /**
    *
    * @param no
    * @return
    */
  def findEmpByNo(no:Int):Emp={
    //辅助指针
    if (head == null){
      return null
    }
    var curEmp = head
    breakable {
      while (true) {
        if (curEmp.no == no) {
          break()
        }
        if (curEmp.next == null) {
          curEmp = null
          break()
        }
        curEmp = curEmp.next
      }

    }
     curEmp
  }
  //添加雇员
  //直接加入链表最后
  def addEmp(emp: Emp):Unit={
    if (head == null){
      head = emp
    }else {
      //使用辅助指针
      var curEmp = head
      //将curEmp定位到链表的最后
      breakable {
        while (true) {
          if (curEmp.next == null) {
            break()
          }
          curEmp = curEmp.next
        }
      }
      curEmp.next = emp
    }
  }

  //遍历该链表
  def list(no:Int):Unit= {
    if (head == null) {
      println()
      println("第"+no+"当前链表情况->")
      return
    }
    //使用辅助指针遍历
    var curTemp = head
    println()
    print("第"+no+"当前链表情况->")
    breakable {
      while (true) {
        printf("no=%d name=%s->", curTemp.no, curTemp.name)
        if (curTemp.next == null) {
          break()
        }
        curTemp = curTemp.next
      }
    }
  }
}

相关推荐