跳表 skip_list

alt

 
package data_structure

import (
	"math"
	"math/rand/v2"
)

const MaxLv = 11

type Node struct {
	value int          // 节点值
	level int          // 节点拥有最高层数
	next  [MaxLv]*Node // 每一层的下一个节点
}

type Skiplist struct {
	head     *Node // 头节点
	curLevel int   // 当前跳表的最高层数
}

func Constructor() Skiplist {
	sl := Skiplist{
		head: &Node{
			value: math.MinInt64,
			level: 0,
			next:  [MaxLv]*Node{},
		},
	}

	sl.curLevel = 0
	return sl
}

func randomLevel() int {
	level := 0
	for rand.Float32() < 0.5 && level+1 < MaxLv {
		level++
	}
	return level
}

func (this *Skiplist) Search(target int) bool {
	curNode := this.head
	for i := this.curLevel; i >= 0; i-- {
		for curNode.next[i] != nil && curNode.next[i].value <= target {
			curNode = curNode.next[i]
		}
		if curNode.value == target {
			return true
		}
	}
	return false
}

func (this *Skiplist) Add(num int) {
	level := randomLevel()
	update := [MaxLv]*Node{}
	curNode := this.head
	for i := level; i >= 0; i-- {
		for curNode.next[i] != nil && curNode.next[i].value < num {
			curNode = curNode.next[i]
		}
		update[i] = curNode
	}

	newNode := &Node{
		value: num,
		level: level,
		next:  [MaxLv]*Node{nil},
	}

	for i := 0; i <= level; i++ {
		newNode.next[i] = update[i].next[i]
		update[i].next[i] = newNode
	}

	if level > this.curLevel {
		this.curLevel = level
	}
}

func (this *Skiplist) Erase(num int) bool {
	update := [MaxLv]*Node{}
	curNode := this.head
	for i := this.curLevel; i >= 0; i-- {
		for curNode.next[i] != nil && curNode.next[i].value < num {
			curNode = curNode.next[i]
		}
		update[i] = curNode
	}
	if update[0].next[0] == nil || update[0].next[0].value != num {
		return false
	}

	for i := 0; i <= this.curLevel; i++ {
		if update[i].next[i] != nil && update[i].next[i].value == num {
			update[i].next[i] = update[i].next[i].next[i]
		}
	}

	for this.curLevel > 0 && this.head.next[this.curLevel] == nil {
		this.curLevel--
	}
	return true
}

func (this *Skiplist) PrintSkiplist() {
	for i := MaxLv - 1; i >= 0; i-- {
		cur := this.head.next[i]
		if cur == nil {
			continue
		}
		for cur != nil {
			print(cur.value, "->")
			cur = cur.next[i]
		}
		println("nil")
	}
}

全部评论

相关推荐

牛客nb666号:见天才的门槛罢了查看图片
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务