summaryrefslogtreecommitdiff
path: root/stack.go
blob: ed8917d3601739a291952e9c96dfb8781127a847 (plain)
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
// Package stack implements a simple LIFO Stack for generic values
package stack

// Stack contains generic values
type Stack []interface{}

// NewStack returns a new Stack
func NewStack() Stack {
	return Stack{}
}

// Push adds value at tail
func (s *Stack) Push(v interface{}) {
	*s = append(*s, v)
}

// Insert inserts value at head
func (s *Stack) Insert(v interface{}) {
	*s = append(Stack{v}, *s...)
}

// Pop retrieves value from tail
func (s *Stack) Pop() (v interface{}) {
	if size := len(*s); size > 0 {
		v, *s = (*s)[size-1], (*s)[:size-1]
	}
	return v
}

// Peek returns top value from Stack
func (s Stack) Peek() interface{} {
	return s[len(s)-1]
}

// Swap swapes two top values
func (s Stack) Swap() {
	if size := len(s); size >= 2 {
		s[size-1], s[size-2] = s[size-2], s[size-1]
	}
}

// Depth returns actual size of Stack
func (s Stack) Depth() int {
	return len(s)
}