ltt.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package ctn
  2. type LTT[T any] struct {
  3. Value T
  4. Left *LTT[T]
  5. Right *LTT[T]
  6. Dist uint64
  7. Size uint64
  8. }
  9. func LttNode[T any] (v T, left *LTT[T], right *LTT[T]) *LTT[T] {
  10. var ld = left.GetDist()
  11. var rd = right.GetDist()
  12. if !(ld >= rd) { panic("violation of leftist property") }
  13. return &LTT[T] {
  14. Value: v,
  15. Left: left,
  16. Right: right,
  17. Dist: (1 + rd),
  18. Size: (1 + left.GetSize() + right.GetSize()),
  19. }
  20. }
  21. func LttLeaf[T any] (v T) *LTT[T] {
  22. return &LTT[T] {
  23. Value: v,
  24. Left: nil,
  25. Right: nil,
  26. Dist: 1,
  27. Size: 1,
  28. }
  29. }
  30. func (node *LTT[T]) GetDist() uint64 {
  31. if node != nil {
  32. return node.Dist
  33. } else {
  34. return 0
  35. }
  36. }
  37. func (node *LTT[T]) GetSize() uint64 {
  38. if node != nil {
  39. return node.Size
  40. } else {
  41. return 0
  42. }
  43. }
  44. func (node *LTT[T]) Merge(another *LTT[T], lt LessThanOperator[T]) *LTT[T] {
  45. if node == nil { return another }
  46. if another == nil { return node }
  47. var smaller *LTT[T]
  48. var bigger *LTT[T]
  49. if !(lt(another.Value, node.Value)) {
  50. smaller = node
  51. bigger = another
  52. } else {
  53. bigger = node
  54. smaller = another
  55. }
  56. var v = smaller.Value
  57. var a = smaller.Left
  58. var b = smaller.Right.Merge(bigger, lt)
  59. if a.GetDist() >= b.GetDist() {
  60. return LttNode(v, a, b)
  61. } else {
  62. return LttNode(v, b, a)
  63. }
  64. }
  65. func (node *LTT[T]) Top() (T, bool) {
  66. if node != nil {
  67. return node.Value, true
  68. } else {
  69. return zero[T](), false
  70. }
  71. }
  72. func (node *LTT[T]) Popped(lt LessThanOperator[T]) (T, *LTT[T], bool) {
  73. if node != nil {
  74. var rest = node.Left.Merge(node.Right, lt)
  75. return node.Value, rest, true
  76. } else {
  77. return zero[T](), nil, false
  78. }
  79. }
  80. func (node *LTT[T]) Pushed(v T, lt LessThanOperator[T]) *LTT[T] {
  81. return node.Merge(LttLeaf(v), lt)
  82. }