算法导论示例-ChainedHash

/**
 * 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));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值