数组+链表 实现简单的散列
package com.cai.math; /** * 哈希散列 之:数组+链表(这里将要实现的部分) * 哈希散列是一种数据结构 */ public class HashTabLinked { public static void main(String[] args) { // EmpLinked linked = new EmpLinked(); ArrayLinked.add(new Emp(1,"路飞")); ArrayLinked.add(new Emp(2,"萨博")); ArrayLinked.add(new Emp(3,"索隆")); ArrayLinked.add(new Emp(7,"娜美")); ArrayLinked.add(new Emp(8,"山治")); ArrayLinked.add(new Emp(9,"乔巴")); ArrayLinked.findAll(); } } /** * 数组链表: * 用取模的方法,存放数据到数组对应的位置 */ class ArrayLinked{ private final static int SIZE = 7; //设置数组的长度(默认为7) private final static EmpLinked[] ARRAY_EMP_LINKED= new EmpLinked[SIZE]; //链表的数组 /** * 根据取模方法找出 no存放对应数组的位置 * @param no * @return 数组下角标 */ public static int getIndex(int no){ return no%SIZE; } //实现增,查 public static void add(Emp emp){ //1.查找到要存入数组对应的位置 int index = getIndex(emp.getNo()); //2.如果数组当前位置为空,创建当前位置新的链表;如果已有,直接在当前链表上新增 EmpLinked linked = ARRAY_EMP_LINKED[index]; if(linked == null){ linked = new EmpLinked(); ARRAY_EMP_LINKED[index] = linked; linked.setHead(emp); }else{ linked.add(emp); } } public static void findAll(){ int count = 0; for (EmpLinked empLinked: ARRAY_EMP_LINKED) { System.out.println("第"+(++count)+"条链路"); if(empLinked !=null){ empLinked.findAll(); }else{ System.out.println("当前没有数组"); } } } } /** * 链表 */ class EmpLinked{ private Emp head;//链表的头指针 //实现增查 public void add(Emp emp){ if(head==null){ head = emp; return; } Emp temp = head; while (true){ if((temp.getNext())==null){ temp.setNext(emp); break; } temp = temp.getNext(); } } public void findAll(){ if(head==null){ System.out.println("没有数据"); return; } Emp temp = head; while (true){ System.out.println(temp.toString()); if((temp.getNext())==null){ break; } temp = temp.getNext(); } } public Emp getHead() { return head; } public void setHead(Emp head) { this.head = head; } } /** * 实体 */ class Emp{ private int no; private String name; private Emp next; public Emp(int no,String name){ this.no = no; this.name = name; } public int getNo() { return no; } public String getName() { return name; } public Emp getNext() { return next; } public void setNo(int no) { this.no = no; } public void setName(String name) { this.name = name; } public void setNext(Emp next) { this.next = next; } @Override public String toString() { return "Emp{" + "no=" + no + ", name='" + name + '\'' + '}'; } }
打印:
第1条链路
Emp{no=7, name='娜美'}
第2条链路
Emp{no=1, name='路飞'}
Emp{no=8, name='山治'}
第3条链路
Emp{no=2, name='萨博'}
Emp{no=9, name='乔巴'}
第4条链路
Emp{no=3, name='索隆'}
第5条链路
当前没有数组
第6条链路
当前没有数组
第7条链路
当前没有数组