zoukankan      html  css  js  c++  java
  • golang 实现跳表skiplist

    package main
    
    import (
    	"math/rand"
    	"time"
    	"fmt"
    )
    
    const (
    	P = 0.6
    	MaxLevel = 8
    )
    
    func randomLevel() int {
    	i := 1
    	rand.Seed(time.Now().UnixNano())
    	for i < MaxLevel {
    		p := rand.Float64()
    		if (p < P) {
    			i++
    		} else {
    			break
    		}
    	}
    	return i
    }
    
    type node struct {
    	level int
    	nexts []*node
    	v     int
    }
    
    type skipList struct {
    	head *node
    }
    
    func NewSkipList() *skipList {
    	s := new(skipList)
    	s.head = new(node)
    	s.head.level = MaxLevel
    	s.head.nexts = make([]*node, MaxLevel)
    	return s
    }
    
    func (s *skipList) insert(v int) {
    	l := randomLevel()
    	add := new(node)
    	add.level = l
    	add.nexts = make([]*node, l)
    	add.v = v
    	i := l
    
    	p := s.head
    	for i > 0 {
    		n := p.nexts[i - 1]
    		for n != nil && n.v < v {
    			p = n
    			n = n.nexts[i - 1]
    		}
    		p.nexts[i - 1] = add
    		add.nexts[i - 1] = n
    		i --
    	}
    }
    
    func (s *skipList) search(v int) *node {
    	i := s.head.level
    	p := s.head
    	for i > 0 {
    		n := p.nexts[i - 1]
    		for n != nil && n.v < v {
    			p = n
    			n = n.nexts[i - 1]
    		}
    		if n != nil && n.v == v {
    			return n
    		}
    		i --
    	}
    	return nil
    }
    
    func (s *skipList) delete(d *node) {
    	i := d.level
    	p := s.head
    	for i > 0 {
    		n := p.nexts[i - 1]
    		for n != nil && n.v < d.v {
    			p = n
    			n = n.nexts[i - 1]
    		}
    		p.nexts[i - 1] = d.nexts[i - 1]
    		i --
    	}
    }
    
    func (s *skipList) print() {
    	p := s.head
    	for (p.nexts[0] != nil) {
    		fmt.Println(p.nexts[0].v)
    		p = p.nexts[0]
    	}
    }
    
    func main() {
    	s := NewSkipList()
    	s.insert(8)
    	s.insert(5)
    	s.insert(3)
    	s.insert(7)
    	s.insert(4)
    	s.insert(9)
    	s.insert(100)
    	s.insert(101)
    	s.insert(55)
    	s.insert(20)
    	s.insert(18)
    	s.insert(11)
    	s.insert(15)
    	s.insert(33)
    	s.print()
    
    	for i := 0; i < 2; i++ {
    		n := s.search(7)
    		if n != nil {
    			fmt.Println("found")
    			s.delete(n)
    		} else {
    			fmt.Println("no found")
    		}
    	}
    
    	s.print()
    }
    

      

    作者:严彦彪 原创作品转载请注明出处
  • 相关阅读:
    uva 10280(欧拉函数)
    uva 11121(-2进制)
    uva 10673(扩展欧几里德)
    uva 106(勾股定理)
    uva 128(简单题)
    Codeforces Round #238 (Div. 1) 解题报告
    2018(1)系统分析/需求分析
    2015(1)进度管理/时间管理
    序列图
    [转贴] 软件测试职业发展的 A 面和 B 面
  • 原文地址:https://www.cnblogs.com/yanbiao/p/12588220.html
Copyright © 2011-2022 走看看