-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpqueue.go
More file actions
98 lines (86 loc) · 1.67 KB
/
pqueue.go
File metadata and controls
98 lines (86 loc) · 1.67 KB
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
95
96
97
98
package pqueue
import (
"container/list"
"sync"
)
type Keytype interface{}
type Valuetype interface {
KeyEqual(interface{}) bool
}
type PQueue struct {
size int64
kvlist *list.List
mp map[Keytype]*list.Element
mtx sync.RWMutex
}
func NewPQueue() *PQueue {
return &PQueue{
size: 0,
kvlist: list.New(),
mp: make(map[Keytype]*list.Element),
}
}
func (pq *PQueue) Size() int64 {
pq.mtx.RLock()
defer pq.mtx.RUnlock()
return pq.size
}
func (pq *PQueue) Get(key Keytype) *list.Element {
pq.mtx.RLock()
defer pq.mtx.RUnlock()
value, ok := pq.mp[key]
if ok {
return value
}
return nil
}
func (pq *PQueue) SetMP(key Keytype, value Valuetype) bool {
ele := pq.Get(key)
if ele != nil {
ele.Value = value
pq.kvlist.MoveToBack(ele)
pq.mp[key] = pq.kvlist.Back()
return true
}
pq.kvlist.PushBack(value)
pq.mp[key] = pq.kvlist.Back()
pq.size++
return false
}
func (pq *PQueue) Set(key Keytype, value Valuetype) bool {
pq.mtx.Lock()
defer pq.mtx.Unlock()
for i := pq.kvlist.Front(); i != nil; i = i.Next() {
v := i.Value.(Valuetype)
// TODO more definition about KeyEqual
if value.KeyEqual(v) {
i.Value = value
pq.kvlist.MoveToBack(i)
pq.mp[key] = pq.kvlist.Back()
return true
}
}
pq.kvlist.PushBack(value)
pq.mp[key] = pq.kvlist.Back()
pq.size++
return false
}
func (pq *PQueue) GetMin() Valuetype {
pq.mtx.RLock()
defer pq.mtx.RUnlock()
front := pq.kvlist.Front()
if front != nil {
return front.Value.(Valuetype)
}
return nil
}
func (pq *PQueue) DelMin() Valuetype {
pq.mtx.Lock()
defer pq.mtx.Unlock()
front := pq.kvlist.Front()
if front != nil {
pq.size--
return pq.kvlist.Remove(front).(Valuetype)
}
return nil
}