import java.util.ArrayList; /** Skip List class for Lab #5 * We need to have a list of head pointers to point to the beginning of * each list/level. */ public class SkipList { private int height; private int randomInt; private int bitPosition; private ArrayList head; public SkipList() { // To simplify implementation, I'll assume a max height, // and start with height+1 empty rows. height = 8; randomInt = 0xa1b2c3d4; // 1010 0001 1011 0010 1100 0011 1101 0100 bitPosition = 0; // Create list of head pointers. // This is the leftmost tower containing -inf, or for us, 0x80000000. head = new ArrayList(); for (int i = 0; i <= height; ++i) { Node first = new Node(Integer.MIN_VALUE, i); head.add(first); // Create the corresponding right end +inf, or 0x7fffffff. Node last = new Node(Integer.MAX_VALUE, i); // Set the pointers of the first and last node. first.right = last; last.left = first; } // Also, we need to set the up and down pointers for the bookends. for (int i = 0; i <= height; ++i) { if (i != 0) { head.get(i).down = head.get(i - 1); head.get(i).right.down = head.get(i - 1).right; } if (i != height) { head.get(i).up = head.get(i + 1); head.get(i).right.up = head.get(i + 1).right; } } } // Either return the highest node containing the key, or we'll wind up // on the bottom row at the key closest but < the desired key, which would // be the desired insertion point. // From class notes: // Let p = first number in highest list. (Note: let's allow even -inf) // While p.below != null // p = p.below // while p.after <= k // p = p.after // return p. // Note that at all times, there are (height + 1) rows of nodes. // Postcondition: the "search" may be technically unsuccessful, so the // caller must check to see that the node returned has the correct key value. public Node search(int key) { // ADD CODE HERE // This dummy return statement is only here to make the skeleton // version of the program able to compile. return null; } // From class notes: // p = search(k) // Since search unsuccessful, p will be in bottom row. // In bottom row, insert new node q to the right of p. // while random bit == 0 // while p.above == null // p = p.before // p = p.above // insert new node to the right of p. public void add(int key) { // ADD CODE HERE } // We'll actually print it sideways. // For each element in the basement S0, print the appropriate # duplicates // that appear as you traverse up its column/building. public String toString() { StringBuilder build = new StringBuilder(); for (Node i = head.get(0); i != null; i = i.right) { for (Node j = i; j != null; j = j.up) build.append("" + j.getOutputKey() + " "); build.append("\n"); } return build.toString(); } }