scala数据结构-Hash表

文章目录

      • 概述

概述

根据key直接访问在内存存储位置的数据结构,通过一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,加快查找速度,这个映射函数称做散列函数,存放记录的数组为散列表

记录存储的位置=f(key)
这里对应关系f称为散列函数,又称为hash函数,采用散列技术将记录存储在一块连续存储空间中,这块连续存储空间称为散列表或hash表

hash表就是把key通过一个固定的算法函数(哈希函数)转换成一个整形数字,然后将该数字与数组长度取余,取余结构当做数据下标,然后将value存储在以该数字为下标的数组空间中,当hash表进行查询的时候,再次使用hash函数将key转换为对应的数组下标,并定位到该空间获取value,这样就充分利用到数组的定位性能进行数据定位
数据特点:寻址容易.插入和删除困难,因为插入和删除涉及到所有的元素下标的移动修改,链表的特点是插入和删除容易,插入和删除移动的只是该元素对应上下游的指针指向.,因此结合寻址容易,插入和删除也容易的数据结构就是hash表
对于hash表有多重实现方法,最常用的是拉链法
scala数据结构-Hash表_第1张图片

package com.zyd

import scala.io.StdIn
import util.control.Breaks._

object HashTableDemo {
  def main(args: Array[String]): Unit = {
    //创建HashTab
    val hashTab = new HashTab(5)
    //写一个简单的菜单
    var key = " "
    while (true) {
      println("add: ")
      println("list: ")
      println("exit: ")
      key = StdIn.readLine()
      key match {
        case "add" => {
          println("输入id")
          val id = StdIn.readInt()
          println("输入名字:")
          val name = StdIn.readLine()
          val emp = new Emp(id, name)
          hashTab.add(emp)
        }
        case "list" => {
          hashTab.list()
        }
      }
    }
  }
}

//创建Emp类
class Emp(eId: Int, eName: String) {
  val id = eId
  var name = eName
  var next: Emp = null
}

//创建EmpLinkedList
class EmpLinkedList {
  //定义头指针.这里head 直接指向一个雇员
  var head: Emp = null

  /**
   * 添加雇员方法
   * 假定 添加雇员的id是自增的,即雇员分配的id总是从小到大,找到链表的最后加入即可
   */
  def add(emp: Emp): Unit = {
    //如果是第一个雇员
    if (head == null) {
      head = emp
      return
    }
    //定义辅助指针
    var cur = head

    breakable {
      while (true) {
        if (cur.next == null) {
          break()
        }
        cur = cur.next
      }
    }
    // 这时cur 指向链表的最后
    cur.next = emp
  }

  /**
   * 遍历链表的方法
   */
  def list(i: Int): Unit = {

    if (head == null) {
      println(s"第${i}条链表为空...")
      return
    }
    print(s"第${i}条链表信息为:")
    var cur = head
    breakable {
      while (true) {
        if (cur == null) {
          break()
        }
        printf(" => id=%d name=%s", cur.id, cur.name)
        println()
        cur = cur.next
      }
    }
  }

}

class HashTab(val size: Int) {
  val empLinkedListArr: Array[EmpLinkedList] = new Array[EmpLinkedList](size)
  //初始化
  for (i <- 0 until size) {
    empLinkedListArr(i) = new EmpLinkedList
  }

  def add(emp: Emp): Unit = {
    //返回该员工,应该加入到哪条链表
    val empLinkedListNo = hashFun(emp.id)
    this.empLinkedListArr(empLinkedListNo).add(emp)
  }


  def list(): Unit = {
    for (i <- 0 until size) {
      val list1 = empLinkedListArr(i)
      list1.list(i)
    }
  }

  //散列函数
  def hashFun(id: Int): Int = {
    id % size
  }
}

add:
list:
exit:
add
输入id
1
输入名字:
zs
add:
list:
exit:
list
第0条链表为空…
第1条链表信息为: => id=1 name=zs
第2条链表为空…
第3条链表为空…
第4条链表为空…
add:
list:
exit:

你可能感兴趣的:(scala数据结构-Hash表)