skiplist.go 987 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "errors"
  4. "math/rand"
  5. )
  6. type Node struct {
  7. key int
  8. value int
  9. isDelete bool
  10. next *Node
  11. down *Node
  12. }
  13. type SkipList struct {
  14. top *Node
  15. maxLevel int = 12
  16. skipRate int = 4
  17. }
  18. func NewSkipList() SkipList {
  19. var sl SkipList
  20. sl.top = &Node{}
  21. prev := sl.top
  22. for i := 0; i < sl.maxLevel; i++ {
  23. node := &Node{}
  24. prev.down = node
  25. prev = node
  26. }
  27. return sl
  28. }
  29. func (sl *SkipList) Get(key int) (int, error) {
  30. curr := sl.top
  31. for curr != nil {
  32. if curr.next == nil {
  33. curr = curr.down
  34. continue
  35. }
  36. if curr.next.key == key {
  37. return curr.next.value, nil
  38. } else if curr.next.key < key {
  39. curr = curr.next
  40. } else {
  41. curr = curr.down
  42. }
  43. }
  44. return 0, errors.New("Not found")
  45. }
  46. func (sl *SkipList) Insert(key, value int) {
  47. level := sl.randomLevel()
  48. for
  49. }
  50. func (sl *SkipList) randomLevel() int {
  51. lv := 1
  52. for i := rand.Intn(sl.skipRate); i == 0 && lv < sl.maxLevel; i = rand.Intn(sl.skipRate) {
  53. lv++
  54. }
  55. return lv
  56. }
  57. func main() {
  58. }