// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer public class SkipList { // Skiplist class private SkipNode head; // Header node for skiplist -- always there private int level; // Level of the current deepest node // Convention: A level 0 node has 1 pointer (at array index 0) public SkipList() { // Constructor head = new SkipNode(null, 0); // The header is initially at level 0 level = -1; // Indicates no nodes of any level } private void AdjustHead(int newLevel) { // Create a new (larger) head SkipNode temp = head; head = new SkipNode(null, newLevel); for (int i=0; i<=level; i++) head.forward[i] = temp.forward[i]; level = newLevel; } public void print() { // Print out contents of a skiplist SkipNode temp = head; while (temp != null) { System.out.print(temp.value() + ": length is " + temp.forward.length + ":"); for (int i=0; i level) // New node will be deepest AdjustHead(newLevel); // Add null pointers to header SkipNode[] update = new SkipNode[level+1]; // Track end of level SkipNode x = head; // Start at header node for (int i=level; i>=0; i--) { // Search for insert position while((x.forward[i] != null) && (((Elem)x.forward[i].value()).key() < newValue.key())) x = x.forward[i]; update[i] = x; // Keep track of end at level i } x = new SkipNode(newValue, newLevel); // Create new node for (int i=0; i<=newLevel; i++) { // Splice into list x.forward[i] = update[i].forward[i]; // Who x points to update[i].forward[i] = x; // Who y points to } } public Elem search(int searchKey) { // Skiplist Search SkipNode x = head; // Dummy header node for (int i=level; i>=0; i--) // For each level... while ((x.forward[i] != null) && // go forward (((Elem)x.forward[i].value()).key() < searchKey)) x = x.forward[i]; // Go one last step x = x.forward[0]; // Move to actual record, if it exists if ((x != null) && (((Elem)x.value()).key() == searchKey)) return (Elem)x.value(); // Got it else return null; // Its not there } }