1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| package structrue.skipList;
import java.util.Random;
public class SkipList <T>{ private SkipListNode<T> head,tail; private int nodes; private int listLevel; private Random random; private static final double PROBABILITY=0.5; public SkipList() { random=new Random(); clear(); }
public void clear(){ head=new SkipListNode<T>(SkipListNode.HEAD_KEY, null); tail=new SkipListNode<T>(SkipListNode.TAIL_KEY, null); horizontalLink(head, tail); listLevel=0; nodes=0; } public boolean isEmpty(){ return nodes==0; }
public int size() { return nodes; }
private SkipListNode<T> findNode(int key){ SkipListNode<T> p=head; while(true){ while (p.right.key!=SkipListNode.TAIL_KEY && p.right.key<=key) { p=p.right; } if (p.down!=null) { p=p.down; }else { break; }
} return p; }
public SkipListNode<T> search(int key){ SkipListNode<T> p=findNode(key); if (key==p.getKey()) { return p; }else { return null; } }
public void put(int k,T v){ SkipListNode<T> p=findNode(k); if (k==p.getKey()) { p.value=v; return; } SkipListNode<T> q=new SkipListNode<T>(k, v); backLink(p, q); int currentLevel=0; while (random.nextDouble()<PROBABILITY) { if (currentLevel>=listLevel) { listLevel++; SkipListNode<T> p1=new SkipListNode<T>(SkipListNode.HEAD_KEY, null); SkipListNode<T> p2=new SkipListNode<T>(SkipListNode.TAIL_KEY, null); horizontalLink(p1, p2); vertiacallLink(p1, head); vertiacallLink(p2, tail); head=p1; tail=p2; } while (p.up==null) { p=p.left; } p=p.up;
SkipListNode<T> e=new SkipListNode<T>(k, null); backLink(p, e); vertiacallLink(e, q); q=e; currentLevel++; } nodes++; } private void backLink(SkipListNode<T> node1,SkipListNode<T> node2){ node2.left=node1; node2.right=node1.right; node1.right.left=node2; node1.right=node2; }
private void horizontalLink(SkipListNode<T> node1,SkipListNode<T> node2){ node1.right=node2; node2.left=node1; }
private void vertiacallLink(SkipListNode<T> node1,SkipListNode<T> node2){ node1.down=node2; node2.up=node1; }
@Override public String toString() { if (isEmpty()) { return "跳跃表为空!"; } StringBuilder builder=new StringBuilder(); SkipListNode<T> p=head; while (p.down!=null) { p=p.down; }
while (p.left!=null) { p=p.left; } if (p.right!=null) { p=p.right; } while (p.right!=null) { builder.append(p); builder.append("\n"); p=p.right; }
return builder.toString(); }
}
|