-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
62 lines (52 loc) · 1.16 KB
/
stack.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
// @Title
// @Description
// @Author
// @Update
package utilities
import (
"fmt"
"sync"
)
// Defines a stack data structure implemented by linked list
type Stack struct {
Common
}
func NewStack(maxCapacity uint) (*Stack, error) {
stack := Stack{
Common: Common{
Ds: NewLinkedList(HEAD),
Mu: sync.Mutex{},
MaxCapacity: maxCapacity,
},
}
if stack.IsMaximumMemoryExceeded() {
return nil, fmt.Errorf("Stack max capicity, exceeded Maximum memory space")
}
return &stack, nil
}
// Inserts item to the top of the stack
// Receives interface{} item to insert
func (s *Stack) Push(val interface{}) error {
s.Mu.Lock()
defer s.Mu.Unlock()
if s.IsMaxCapicityExcedded() {
return fmt.Errorf("Maximum capacity exceeded")
}
s.Ds.(*LinkedList).AddElement(val)
s.Top = s.Ds.(*LinkedList).GetHead()
s.NumOfElements++
return nil
}
// Removes item from the top of the stack
func (s *Stack) Pop() (interface{}, error) {
s.Mu.Lock()
defer s.Mu.Unlock()
if s.IsEmpty() {
return nil, fmt.Errorf("Stack is empty")
}
temp := s.Top.GetVal()
s.Ds.DeleteElement(s.Top)
s.Top = s.Ds.(*LinkedList).GetHead()
s.NumOfElements--
return temp, nil
}