-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
71 lines (61 loc) · 1.58 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
63
64
65
66
67
68
69
70
71
package datastructures
import (
"errors"
)
type Stack struct {
linkedList *DoublyLinkedList
}
// NewStack returns a new stack data structure.
func NewStack() *Stack {
return &Stack{
linkedList: NewDoublyLinkedList(),
}
}
// Size returns the current size of the stack.
func (s *Stack) Size() int {
return s.linkedList.Size()
}
// IsEmpty returns true if the stack is empty else false.
func (s *Stack) IsEmpty() bool {
return s.linkedList.IsEmpty()
}
// Push adds a new item to the stack.
func (s *Stack) Push(item interface{}) *Stack {
s.linkedList.AddHead(&DoublyLinkedListNode{Data: item})
return s
}
// Pop removes the top element from the stack.
func (s *Stack) Pop() (interface{}, error) {
headNode := s.linkedList.GetHead()
if headNode == nil {
return nil, errors.New("stack is empty")
}
s.linkedList.RemoveHead()
return headNode.Data, nil
}
// Peek returns the top element in the stack without removing it.
func (s *Stack) Peek() (interface{}, error) {
headNode := s.linkedList.GetHead()
if headNode == nil {
return nil, errors.New("stack is empty")
}
return headNode.Data, nil
}
// Iterate iterates through stack and executes the callback function
// f for each iteration.
func (s *Stack) Iterate(f func(index int, item interface{})) {
s.linkedList.Iterate(func(index int, node *DoublyLinkedListNode) {
f(index, node.Data)
})
}
// Contains returns true if the item is in the stack; else false.
func (s *Stack) Contains(item interface{}) bool {
var exist bool
s.Iterate(func(index int, elem interface{}) {
if item == elem {
exist = true
return
}
})
return exist
}