/** * 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 发布