summaryrefslogtreecommitdiff
path: root/stack.go
blob: 4f9d4c01f4eb952a78a03fa7411005fd1ff792be (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
46
47
48
// Package stack implements a simple LIFO Stack for generic values
package stack

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

// New allocates a new Stack
func New() *Stack {
	return new(Stack)
}

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

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

// Pop 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 a top value on Stack
func (s Stack) Peek() (v interface{}) {
	if size := len(s); size > 0 {
		v = s[size-1]
	}
	return v
}

// Swap 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)
}