-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathleftistHeap.go
94 lines (81 loc) · 1.79 KB
/
leftistHeap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package heap
type ltHeapElement struct {
left, right *ltHeapElement
dist int
Value interface{}
}
type ltHeapArray struct {
root *ltHeapElement
len int
}
func (h *ltHeapArray) Left(i interface{}) interface{} {
iE := i.(*ltHeapElement)
return iE.left
}
func (h *ltHeapArray) Right(i interface{}) interface{} {
iE := i.(*ltHeapElement)
return iE.right
}
func (h *ltHeapArray) Head() interface{} {
return h.root
}
func (h *ltHeapArray) Swap(i interface{}, j interface{}) {
iE := i.(**ltHeapElement)
jE := j.(**ltHeapElement)
(*iE), (*jE) = (*jE), (*iE)
}
func (h *ltHeapArray) Key(i interface{}) int {
iE := i.(*ltHeapElement)
return iE.Value.(int)
}
func (h *ltHeapArray) Value(i interface{}) interface{} {
iE := i.(*ltHeapElement)
return iE.Value
}
func (h *ltHeapArray) Len() int {
return h.len
}
func (h *ltHeapArray) Pop() (i interface{}) {
i = h.root.Value
h.root = h.merge(h.root.left, h.root.right).(*ltHeapElement)
h.len--
return
}
func (h *ltHeapArray) Append(i interface{}) {
newE := ltHeapElement{Value: i}
h.root = h.merge(h.root, &newE).(*ltHeapElement)
h.len++
}
//merge:O(logn)
func (h *ltHeapArray) merge(i interface{}, j interface{}) interface{} {
iE := i.(*ltHeapElement)
jE := j.(*ltHeapElement)
if iE == nil {
return jE
}
if jE == nil {
return iE
}
if h.Key(iE) < h.Key(jE) {
h.Swap(&iE, &jE)
}
iE.right = h.merge(iE.right, jE).(*ltHeapElement)
if iE.left == nil || iE.right.dist > iE.left.dist {
h.Swap(&iE.left, &iE.right)
}
if iE.right == nil {
iE.dist = 0
} else {
iE.dist = iE.right.dist + 1
}
return iE
}
func (h *ltHeapArray) Union(i interface{}) interface{} {
_i := i.(*ltHeapArray)
h.root = h.merge(h.root, _i.root).(*ltHeapElement)
h.len += _i.len
return h
}
func newLtHeapArray() *ltHeapArray {
return new(ltHeapArray)
}