|
| 1 | +/* |
| 2 | + * To change this license header, choose License Headers in Project Properties. |
| 3 | + * To change this template file, choose Tools | Templates |
| 4 | + * and open the template in the editor. |
| 5 | + */ |
| 6 | +package designskiplist; |
| 7 | + |
| 8 | +import java.util.Random; |
| 9 | +import java.util.Stack; |
| 10 | + |
| 11 | +/** |
| 12 | + * |
| 13 | + * @author souravpalit |
| 14 | + */ |
| 15 | +public class SkipList { |
| 16 | + |
| 17 | + private Node head; |
| 18 | + private int DUMMY_VALUE = -1; |
| 19 | + private Random randomGenerator; |
| 20 | + |
| 21 | + public SkipList() { |
| 22 | + head = new Node(DUMMY_VALUE); // dummy Node |
| 23 | + randomGenerator = new Random(); |
| 24 | + } |
| 25 | + |
| 26 | + public boolean search(int target) { |
| 27 | + Node current = head; |
| 28 | + |
| 29 | + while (current != null) { |
| 30 | + while (current.next != null && current.next.val < target) { |
| 31 | + current = current.next; |
| 32 | + } |
| 33 | + |
| 34 | + if (current.next != null && current.next.val == target) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + // Not found so go down |
| 38 | + current = current.down; |
| 39 | + } |
| 40 | + |
| 41 | + return false; |
| 42 | + } |
| 43 | + |
| 44 | + public void add(int target) { |
| 45 | + Stack<Node> path = new Stack<Node>(); |
| 46 | + Node current = head; |
| 47 | + while (current != null) { |
| 48 | + while (current.next != null && current.next.val < target) { |
| 49 | + current = current.next; |
| 50 | + } |
| 51 | + |
| 52 | + path.push(current); |
| 53 | + current = current.down; |
| 54 | + } |
| 55 | + |
| 56 | + boolean goUp = true; |
| 57 | + Node down = null; |
| 58 | + |
| 59 | + while (goUp && !path.isEmpty()) { |
| 60 | + current = path.pop(); |
| 61 | + current.next = new Node(target, current.next, down); |
| 62 | + down = current.next; |
| 63 | + goUp = getRandomNumber(1, 100) < 50; |
| 64 | + } |
| 65 | + |
| 66 | + if (goUp) { |
| 67 | + head = new Node(DUMMY_VALUE, null, head);; |
| 68 | + } |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | + public boolean erase(int target) { |
| 73 | + Node current = head; |
| 74 | + boolean found = false; |
| 75 | + |
| 76 | + while (current != null) { |
| 77 | + while (current.next != null && current.next.val < target) { |
| 78 | + current = current.next; |
| 79 | + } |
| 80 | + |
| 81 | + if (current.next != null && current.next.val == target) { |
| 82 | + found = true; |
| 83 | + current.next = current.next.next; |
| 84 | + } |
| 85 | + |
| 86 | + // May present down also |
| 87 | + current = current.down; |
| 88 | + } |
| 89 | + |
| 90 | + return found; |
| 91 | + } |
| 92 | + |
| 93 | + public int getRandomNumber(int min, int max) { |
| 94 | + return randomGenerator.nextInt(max - min) + min; |
| 95 | + } |
| 96 | +} |
0 commit comments