- 论坛徽章:
- 0
|
这个是网上找到的一个hashtable地实现
/** * Introduction to Algorithms, Second Edition
* 11.4 Open addressing tables * @author 土豆爸爸 * */
public class HashTable {
/** * 数据节点 */
public static class Node {
int key;
public Node(int key) {
this.key = key;
}
}
private Node[] table; //直接寻址表
private Node deleted = new Node(0);
/** * 构造函数。 * @param size 表大小 */
public HashTable(int size)
{
table = new Node[size];
}
/**
* 根据键值k查找节点。需要跳过标记为deleted的位置
* @param k 节点的键值
* @return 键值为k的节点,未找到返回null
*/
public Node search(int k)
{
for(int i = 0; i < table.length;i++)
{
int j = hash(k, i);
if(table[j] == null) {
return null;
} else if(table[j] != deleted && table[j].key == k) {
return table[j];
}
}
return null;
}
/**
* 插入节点x。根据x.key计算哈希值,如果哈希值对应的位置
* 已被占据,查找下一个,直到找到一个空位或标记为deleted的位置。
* @param x 待插入节点
*/
public void insert(Node x) {
for(int i = 0; i < table.length;i++)
{
int j = hash(x.key, i);
if(table[j] == deleted || table[j] == null) {
table[j] = x;
return;
}
}
throw new RuntimeException("Over flow");
}
/**
* 删除节点x。将删除节点标记为deleted。
* @param x 待删除节点
*/
public void delete(Node x) {
for(int i = 0; i < table.length;i++) {
int j = hash(x.key, i);
if(table[j] == x) {
table[j] = deleted;
break;
}
}
}
/**
* 计算哈希值
* @param key 键值
* @return 哈希值
*/
private int hash(int key, int i) {
int m = table.length;
return (key % m + i) % m;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < table.length; i++) {
if (table[i] == null) {
sb.append("null\t");
} else {
sb.append(table[i].key).append("\t");
}
}
return sb.toString();
}
}
import junit.framework.TestCase;
public class HashTableTest extends TestCase
{
public void testLinkedList() {
HashTable table = new HashTable(100);
// 插入100个随机节点
for (int i = 0; i < 100; i++) {
int key = (int) (Math.random() * 1000);
if (table.search(key) == null) {
table.insert(new HashTable.Node(key));
}
}
System.out.println(table);
// 找到一个节点
HashTable.Node node = null;
for (int i = 0; i < 100; i++) {
node = table.search(i);
if (node != null) {
break;
}
}
assertNotNull(node);
table.delete(node);
assertEquals(null, table.search(node.key));
}
} |
|