/// <summary> /// find the node, if not found, return null /// </summary> /// <param name="key"></param> /// <returns></returns> public SkipListNode <K, V> Search(K key) { if (supportList.Count <= 0) { return(null); } SortedSkipLinkedList <K, V> sh = supportList[supportList.Count - 1]; if (sh.HeadNode == null) { return(null); } SkipListNode <K, V> node = sh.HeadNode; SkipListNode <K, V> rightNode = node.Next; while (true) { //reach to end if (rightNode.IsMaxNode) { node = node.Down; if (node == null) { return(null); } else { rightNode = node.Next; continue; } } int result = rightNode.Key.CompareTo(key); if (result == 0) { return(rightNode); } else if (result >= 0) { node = node.Down; if (node == null) { return(null); } else { rightNode = node.Next; } } else { node = node.Next; rightNode = node.Next; } } }
/// <summary> /// if randonDecision = true, increase height by 1, else just insert /// </summary> /// <param name="key"></param> /// <param name="val"></param> public void Insert(K key, V val) { Count++; bool decision = RandomDecision(); int height = 1; while (decision) { //increase height by 1; height++; decision = RandomDecision(); } while (supportList.Count < height) { var listn = new SortedSkipLinkedList <K, V>(); if (supportList.Count > 0) { var listn_1 = supportList[supportList.Count - 1]; listn_1.HeadNode.Up = listn.HeadNode; listn.HeadNode.Down = listn_1.HeadNode; listn_1.TailNode.Up = listn.TailNode; listn.TailNode.Down = listn_1.TailNode; } supportList.Add(listn); } //the height column var sh = supportList[height - 1]; var insertPoint = sh.SearchInsertPoint(key); SkipListNode <K, V> upNode = null; while (insertPoint != null) { var newNode = new SkipListNode <K, V>(key, val); newNode.Next = insertPoint.Next; newNode.Prev = insertPoint; insertPoint.Next.Prev = newNode; insertPoint.Next = newNode; sh.Count++; if (upNode != null) { upNode.Down = newNode; newNode.Up = upNode; } upNode = newNode; insertPoint = insertPoint.Down; if (insertPoint == null) { break; } var rightNode = insertPoint.Next; while (true) { if (rightNode.IsMaxNode) { break; } if (rightNode.Key.CompareTo(key) < 0) { insertPoint = rightNode; rightNode = insertPoint.Next; } else { break; } } height--; sh = supportList[height - 1]; } }