其实现不难,所以直接贴代码:
1 package dataSrtuct; 2 3 import java.util.ArrayList; 4 import java.util.LinkedList; 5 6 public class HashTab { 7 public static void main(String[] args) { 8 hashTable hashT=new hashTable(10); 9 hashT.addNode(new Emp(12,"Mlq")); 10 hashT.addNode(new Emp(13,"Zbb")); 11 hashT.addNode(new Emp(14,"Myp")); 12 hashT.addNode(new Emp(15,"Mxp")); 13 hashT.addNode(new Emp(16,"Mll")); 14 hashT.addNode(new Emp(17,"Ylz")); 15 Emp node = hashT.findNode(16); 16 System.out.println(node.id + node.name); 17 } 18 } 19 //哈希表 20 class hashTable{ 21 private EmpList[] empLists; 22 private Integer size; 23 24 public hashTable(Integer size) { 25 this.empLists = new EmpList[size]; 26 this.size = size; 27 //避免为空 28 for (int i = 0; i < empLists.length; i++) { 29 empLists[i]=new EmpList(); 30 } 31 } 32 33 /** 34 * 简单散列函数 35 * @param id 标志 36 * @return 散列值 37 */ 38 public Integer hashCode(Integer id){ 39 return id%size; 40 } 41 42 /** 43 * 添加节点 44 * @param emp 目标节点 45 */ 46 public void addNode(Emp emp){ 47 Integer hashC=hashCode(emp.id); 48 empLists[hashC].addNode(emp); 49 } 50 51 /** 52 * 查找节点 53 * @param id 查找的标志 54 * @return 目标节点 55 */ 56 public Emp findNode(Integer id){ 57 Integer hashC=hashCode(id); 58 return empLists[hashC].findNode(id); 59 } 60 } 61 //对象信息 62 class Emp{ 63 public Integer id; 64 public String name; 65 public Emp next; 66 67 public Emp(Integer id, String name) { 68 this.id = id; 69 this.name = name; 70 } 71 } 72 //单个对象链表 73 class EmpList{ 74 public Emp head; 75 76 /** 77 * 添加哈希表的内部链表节点 78 * @param emp 目标添加节点 79 * @return 链表节点 80 */ 81 public Emp addNode(Emp emp){ 82 if (head==null){ 83 head=emp; 84 } 85 else { 86 Emp curNext=head; 87 while (curNext.next!=null){ 88 curNext=curNext.next; 89 } 90 curNext.next=emp; 91 } 92 return head; 93 } 94 95 /** 96 * 返回查找的哈希表值 97 * @param id 查找信息的唯一标志 98 * @return 相对应的对象信息 99 */ 100 public Emp findNode(Integer id){ 101 Emp curNext=head; 102 Emp idNext=null; 103 while(curNext!=null){ 104 if (curNext.id.equals(id)){ 105 idNext=curNext; 106 break; 107 } 108 curNext= curNext.next; 109 } 110 return idNext; 111 } 112 113 /** 114 * 删除目标节点 115 * @param id 标志 116 * @return 删除标志, 117 */ 118 public boolean deleteNode(Integer id){ 119 Emp idNext=findNode(id); 120 idNext.id=idNext.next.id; 121 idNext.name=idNext.next.name; 122 idNext.next=idNext.next.next; 123 if (idNext==null) 124 return false; 125 else 126 return true; 127 } 128 129 /** 130 * 展示当前链表的信息 131 */ 132 public void listShow(){ 133 if (head==null) 134 System.out.println("此链表为空"); 135 else { 136 Emp curNext=head; 137 while (curNext!=null){ 138 System.out.println("此链表的信息为:"); 139 System.out.print(curNext.id +":"+ curNext.name+" "); 140 curNext=curNext.next; 141 } 142 } 143 } 144 }
标签:Java,public,curNext,Emp,哈希,return,next,散列,id From: https://www.cnblogs.com/Mexcellent/p/17280988.html