-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
57 lines (47 loc) · 1.3 KB
/
stack.go
File metadata and controls
57 lines (47 loc) · 1.3 KB
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
// Copyright 2014, Ali Najafizadeh. All rights reserved.
// Use of this source code is governed by a BSD-style
// Author: Ali Najafizadeh
//Inspired by: https://gist.github.com/bemasher/1777766
// As the header implies, this is copy-pasta'd for simplicity. In the
// real-world, do thing this as a linked list is silly for speed reasons
// (arrays and slices in go would be SUPER fast by comparison), I just didn't
// want to write Yet Another Goddamn Stack (tm)
package util
//Stack the implementation of stack
//this stack is not thread safe!
type Stack struct {
top *item
size int
}
//Len returns the size of stack
func (s *Stack) Len() int {
return s.size
}
//Push pushs a value to the top of stack
func (s *Stack) Push(value interface{}) {
s.top = &item{
value: value,
next: s.top,
}
s.size++
}
//Pop returns a top value. make sure to check exists
//it is possible to push nil value. So again check the exists value
func (s *Stack) Pop() (value interface{}, exists bool) {
exists = false
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
exists = true
}
return
}
//Peek returns a top without removing it from list
func (s *Stack) Peek() (value interface{}, exists bool) {
exists = false
if s.size > 0 {
value = s.top.value
exists = true
}
return
}