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