package com.chazhao;
class Node {
int index;
int data;
Node next = null;
public Node() {
}
}
class Hash {
int len, mid, low, high;
Node n[] = new Node[10];// 如果数据量多,可适当修改
int a[] = new int[100];
public Hash() {
for (int i = 0; i < len; i++) {
n[i] = null;
}
}
// 创建a[],便于使用
public void create(int[] temp) {
System.out.println("创建数组为:");
System.out.print(a[0] + " ");
for (int i = 1; i <= len; i++) {
a[i] = temp[i - 1];
System.out.print(a[i] + " ");
}
System.out.println();
}
// 输出链式存储哈希表
public void show_hash() {
int i;
Node t_node = null;
for (i = 0; i < len; i++) {
t_node = n[i];
while (t_node != null) {
System.out.print(t_node.data + " ");
t_node = t_node.next;
}
System.out.println();
}
}
// 创建链式存储
public void create_hash() {
System.out.println("创建链式存储hash表结构为:");
int i, id;
Node t_node = null;
for (i = 1; i <= len; i++) {
id = a[i] % len;
if (n[id] == null) {
n[id] = new Node();
n[id].index = i;
n[id].data = a[i];
} else if (n[id] != null) {
t_node = n[id];
while (t_node.next != null) {
t_node = t_node.next;
}
t_node.next = new Node();
t_node.next.data = a[i];
t_node.next.index = i;
}
System.out.print(a[i] + " ");
}
System.out.println();
}
// 进行hash查找
public void chazhao_hash(int key) {
System.out.println("进行数据查找:");
int i;
Node t_node = null;
boolean is = false;
for (i = 0; i < len; i++) {
// n[i] = new Node();
t_node = n[i];
while (t_node != null) {
if (t_node.data == key) {
System.out.println("索引为:" + t_node.index + " " + "数据为:" + t_node.data);
is = true;
}
t_node = t_node.next;
}
}
if (!is) {
System.out.println("未查询到数据!");
}
}
}
public class hash_chazhao {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hash px = new Hash();
int t[] = { 10, 20, 30, 40, 50, 11, 22, 33, 44, 55 };
px.len = 10;
px.create(t);
px.create_hash();
px.show_hash();
px.chazhao_hash(10);
}
}
所有评论(0)