算法导论示例-SentinelLinkedList

/**
 * Introduction to Algorithms, Second Edition 
 * 10.2 SentinelLinkList
 * @author 土豆爸爸
 * 
 */
public class SentinelLinkList {
    /**
     * 链表节点
     */
    public static class Node {
        int key;
        Node prev; // 当前节点的前驱节点
        Node next; // 当前节点的后继节点

        public Node(int key) {
            this.key = key;
        }
    }

    private Node nul;

    /**
     * 构造函数。初始化nul,使nul的前驱和后继都指向它自己。
     */
    public SentinelLinkList() {
        nul = new Node(0);
        nul.prev = nul;
        nul.next = nul;
    }
    
    /**
     * 查找键值为key的节点
     * @param key 待查找节点的键值
     * @return 键值为key的节点,如果没有找到返回null
     */
    public Node search(int key) {
        Node x = nul.next;
        while (x != nul && x.key != key) {
            x = x.next;
        }
        return x;
    }

    /**
     * 插入节点x。在链表的最前面插入。
     * @param x 待插入节点
     */
    public void insert(Node x) {
        x.next = nul.next; // 使x的后继指向原来的nul的后继
        nul.next.prev = x; // 使nul的后继的前驱指向x
        nul.next = x; // 使nul的后继指向x
        x.prev = nul; // 使x的前驱指向nul
    }

    /**
     * 删除节点x。
     * @param x 待删除节点
     */
    public void delete(Node x) {
        x.prev.next = x.next; // 使x的前驱的后继指向x的后继
        x.next.prev = x.prev; // 使x的后继的前驱指向x的前驱
    }
}

import junit.framework.TestCase;

public class SentinelLinkedListTest extends TestCase{
    public void testLinkedList(){
        SentinelLinkList list = new SentinelLinkList();
        SentinelLinkList.Node n1, n2, n3;
        list.insert(n1 = new SentinelLinkList.Node(1));
        list.insert(n2 = new SentinelLinkList.Node(2));
        list.insert(n3 = new SentinelLinkList.Node(3));
        
        assertEquals(n3, list.search(3));
        assertEquals(n2, list.search(2));
        assertEquals(n1, list.search(1));
        assertEquals(n3, n2.prev);
        assertEquals(n1, n2.next);
        
        list.delete(n2);
        assertEquals(n3, n1.prev);
        assertEquals(n1, n3.next);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值