funcConstructor() Skiplist { var skiplist Skiplist var node Node skiplist.root = &node skiplist.currentLevel = 0 return skiplist }
func(sk *Skiplist) Search(target int) bool { _, ok := search(sk.root, target) return ok }
funcsearch(root *Node, target int) (node *Node, ok bool) { for i := len(root.Next) - 1; i >= 0; i-- { var head = root.Next[i] if head == nil || head.Val > target { continue } if head.Val == target { node, ok = head, true return } if head.Val < target { // 小于则向下 root = head i = len(root.Next) continue } } return }
funcadd(root *Node, node *Node) { for i := len(root.Next) - 1; i >= 0; i-- { var head = root.Next[i] if head == nil { if i < len(node.Next) { root.Next[i] = node node.Prev[i] = root } continue } if head.Val >= node.Val { if i < len(node.Next) { root.Next[i] = node node.Next[i] = head node.Prev[i] = root node.Next[i].Prev[i] = node } continue } if head.Val < node.Val { root = head i = len(root.Next) continue } } }
// 移除元素,然后直接 func(sk *Skiplist) Erase(num int) bool { node, ok := search(sk.root, num) if !ok { returnfalse } for i := 0; i < len(node.Next); i++ { node.Prev[i].Next[i] = node.Next[i] if node.Next[i] != nil { node.Next[i].Prev[i] = node.Prev[i] } } returntrue }