算法导论示例-DirectAddressTable

/**
 * 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));
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值