-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.go
68 lines (56 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
package stack
type Stack struct {
elements []interface{}
}
// Init initializes the set
func (stack *Stack) Init() *Stack {
stack.elements = make([]interface{}, 0)
return stack
}
func New(elements ...[]interface{}) *Stack {
if elements == nil || len(elements) < 1 {
return new(Stack).Init()
}
// covert slice to node
// Create a new node.
var element []interface{}
// Iterate over the list and create a node for each value.
for _, item := range elements {
// append slice to the end of the list
element = append(element, item...)
}
// Create a new node.
return &Stack{element}
}
// Push : Adds a new element to the end of the stack.
func (stack *Stack) Push(element interface{}) {
// append item to element
stack.elements = append(stack.elements, element)
}
// Pop : removes the last element from the end of the stack.
func (stack *Stack) Pop() {
// slice the array to the last item
stack.elements = stack.elements[:len(stack.elements)-1]
}
// Size returns the size of the stack
func (stack *Stack) Size() int {
return len(stack.elements)
}
// Reverse : reverses the Stack
func (stack *Stack) Reverse() {
for i, j := 0, len(stack.elements)-1; i < j; i, j = i+1, j-1 {
stack.elements[i], stack.elements[j] = stack.elements[j], stack.elements[i]
}
}
// ToMap : converts the stack to a map
func (stack *Stack) ToMap() map[int]interface{} {
var mapStack = make(map[int]interface{})
for i, value := range stack.elements {
mapStack[i] = value
}
return mapStack
}
// ToArray : converts the stack to an array
func (stack *Stack) ToArray() []interface{} {
return stack.elements
}