forked from gofor-little/ts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list.go
More file actions
71 lines (55 loc) · 1.12 KB
/
linked_list.go
File metadata and controls
71 lines (55 loc) · 1.12 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
package ts
import (
"sync"
)
// LinkedList is a thread safe first in first out (FIFO) list.
type LinkedList struct {
head *LinkedListItem
tail *LinkedListItem
mutex sync.RWMutex
}
// Push pushes a new item to the end of the LinkedList.
func (l *LinkedList) Push(value interface{}) {
l.mutex.Lock()
defer l.mutex.Unlock()
item := &LinkedListItem{
Value: value,
next: nil,
}
if l.tail != nil {
l.tail.next = item
}
l.tail = item
if l.head == nil {
l.head = l.tail
}
}
// Pop pops the first item from the start of the LinkedList.
func (l *LinkedList) Pop() interface{} {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.head == nil {
return nil
}
value := l.head.Value
l.head = l.head.next
if l.head == nil {
l.tail = nil
}
return value
}
// IsEmpty checks if the LinkedList is empty.
func (l *LinkedList) IsEmpty() bool {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.head == nil
}
// GetTail returns a copy of the value in the last item of the LinkedList.
func (l *LinkedList) GetTail() interface{} {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.tail == nil {
return nil
}
return l.tail.Value
}