package HashTable;
public class HashTable {
LinkedList[] hashList;//存放链表的数组
int size;//哈希表长度
//构造方法
public HashTable(int size) {
this.size = size;
this.hashList = new LinkedList[size];
for (int i = 0; i < size; i++) {
hashList[i] = new LinkedList();
}
}
//求一个数的哈希码,返回int类型,用除以哈希表长度去余数的方法
//负数就再加上长度
public int hash(int data){
int hashCode = data % this.size;
if (hashCode < 0){
hashCode = hashCode + this.size;
}
return hashCode;
}
public void insertHash(int data){
int hashCode = hash(data);
hashList[hashCode].insertElem(data);
}
public void deleteHash(int data){
int hashCode = hash(data);
hashList[hashCode].deleteElem(data);
}
public void displayHash(){
for (int i = 0; i < this.size; i++){
System.out.print("hashList " + i + ":");
hashList[i].display();
}
}
//测试
public static void main(String[] args) {
HashTable h = new HashTable(10);
h.insertHash(13);
h.insertHash(16);
h.insertHash(34);
h.insertHash(78);
h.insertHash(-12);
h.displayHash();
}
}
//结点类
class Node{
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
//链表类
class LinkedList{
int size;
Node head;
public LinkedList() {
this.size = 0;
this.head = null;
}
//链表添加元素
public void insertElem(int data){
if (head == null){
head = new Node(data);
this.size ++;
}
else {
Node item = head;
while (item.next != null){
item = item.next;
}
item.next = new Node(data);
this.size ++;
}
}
//链表删除元素
public void deleteElem(int data){
if (head == null){
System.out.println("无此数据");
}
else if (head.val == data) {
this.head = head.next;
this.size --;
}
else {
Node item = head;
while (item.next != null && item.next.val != data){
item = item.next;
}
if (item.next.val == data){
item.next = item.next.next;
this.size --;
}
else{
System.out.println("无此数据");
}
}
}
//打印链表
public void display(){
if (head == null){
System.out.println("null");
}
else{
Node item = head;
while (item != null){
System.out.print(item.val + "-->");
item = item.next;
}
System.out.println("null");
}
}
}
Java实现哈希表数据结构
最新推荐文章于 2024-03-30 09:22:05 发布