private bool Search(SkipListElement anchor, int val) { var e = anchor; while (e != null) { if (e.Value == val) { return(true); } if (e.Next == null || e.Next.Value > val) { break; } e = e.Next; } if (e.Down != null) { return(Search(e.Down, val)); } return(false); }
public void Insert(int val) { var height = GetRandomHeight(); var e = new SkipListElement { Height = 0, Value = val }; if (first.Next == null) { first.Next = e; } else { while (e.Height <= this.listHeight) { var upperElement = new SkipListElement { Height = e.Height + 1, Value = e.Value, Down = e }; e = upperElement; } TraverseSkipList(first, e); } while (e.Height <= height) { var upperElement = new SkipListElement { Height = e.Height + 1, Value = e.Value, Down = e }; e = upperElement; } // increase list height to element height if lower int heightDiff = height - listHeight; while (heightDiff > 0) { var newFirst = new SkipListElement { Down = this.first, Next = e }; this.first = newFirst; e = e.Down; heightDiff--; } this.listHeight = Math.Max(height, listHeight); }
private void TraverseSkipList(SkipListElement anchor, SkipListElement val) { SkipListElement position = FindPosition(anchor, val.Value); if (position.Down != null) { TraverseSkipList(position.Down, val.Down); } UpdateReferences(position, val); }
private SkipListElement FindPosition(SkipListElement element, int val) { while (element != null) { if (element.Next != null && element.Next.Value < val) { element = element.Next; } else { return(element); } } return(element); }
public SkipList() { l0 = new SkipListElement(); first = l0; }
private void UpdateReferences(SkipListElement o, SkipListElement next) { next.Next = o.Next; o.Next = next; }