/**
* Introduction to Algorithms, Second Edition
* 11.1 Direct-address tables
* @author 土豆爸爸
*
*/
public class DirectAddressTable {
/**
* 数据节点
*/
public static class Node {
int key;
public Node(int key) {
this.key = key;
}
}
Node[] table; //直接寻址表
/**
* 构造函数。
* @param maxKey 指定最大可能出现的key值
*/
public DirectAddressTable(int maxKey) {
table = new Node[maxKey + 1];
}
/**
* 查找键值为k的元素
* @param k 待查找元素的键值
* @return 键值为k的元素,未找到返回null
*/
public Node search(int k) {
return table[k];
}
/**
* 插入节点x。直接寻址表的第x.key个元素指向x。
* @param x 待插入节点
*/
public void insert(Node x) {
table[x.key] = x;
}
/**
* 删除节点x。
* @param x 待删除节点
*/
public void delete(Node x) {
table[x.key] = null;
}
}
import junit.framework.TestCase;
public class DirectAddressTableTest extends TestCase{
public void testLinkedList(){
DirectAddressTable table = new DirectAddressTable(3);
DirectAddressTable.Node n1, n2, n3;
table.insert(n1 = new DirectAddressTable.Node(1));
table.insert(n2 = new DirectAddressTable.Node(2));
table.insert(n3 = new DirectAddressTable.Node(3));
assertEquals(n3, table.search(3));
assertEquals(n2, table.search(2));
assertEquals(n1, table.search(1));
table.delete(n2);
assertEquals(null, table.search(2));
}
}
算法导论示例-DirectAddressTable
最新推荐文章于 2022-02-05 12:43:59 发布
本文介绍了一种简单高效的数据结构——直接寻址表,并通过Java代码实现该表的基本操作,包括插入、查找和删除节点。适用于键值范围较小且连续的情况。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Stable-Diffusion-3.5
图片生成
Stable-Diffusion
Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率
1785

被折叠的 条评论
为什么被折叠?



