/** * Introduction to Algorithms, Second Edition * 11.2 Direct-address tables * @author 土豆爸爸 * */ public class ChainedHash { private LinkedList[] table; //哈希表 /** * 构造函数。 * @param slot 指定哈希表的大小 */ public ChainedHash(int slot) { table = new LinkedList[slot]; for(int i = 0; i < slot; i++) { table[i] = new LinkedList(); } } /** * 查找键值为k的元素 * @param k 待查找元素的键值 * @return 键值为k的元素,未找到返回null */ public LinkedList.Node search(int k) { return table[hash(k)].search(k); } /** * 插入节点x。根据x.key计算哈希值,将x插入到哈希表所指向的链表中。 * @param x 待插入节点 */ public void insert(LinkedList.Node x) { table[hash(x.key)].insert(x); } /** * 删除节点x。 * @param x 待删除节点 */ public void delete(LinkedList.Node x) { table[hash(x.key)].delete(x); } /** * 计算哈希值 * @param key 键值 * @return 哈希值 */ private int hash(int key) { return key % table.length; } public void print() { for(int i = 0; i < table.length; i++) { LinkedList.Node head = table[i].getHead(); System.out.print(i + ":"); while(head != null) { System.out.print(head.key + " "); head = head.next; } System.out.println(); } } } import junit.framework.TestCase; public class ChainedHashTest extends TestCase { public void testLinkedList() { ChainedHash table = new ChainedHash(10); // 插入100个随机节点 for (int i = 0; i < 100; i++) { int key = (int) (Math.random() * 1000); if (table.search(key) == null) { table.insert(new LinkedList.Node(key)); } } table.print(); // 找到一个节点 LinkedList.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)); } }
算法导论示例-ChainedHash
最新推荐文章于 2022-03-08 15:40:34 发布