2014-08-11 13:10:38 +00:00
|
|
|
package stack
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
type StackItem struct {
|
|
|
|
item interface{}
|
|
|
|
next *StackItem
|
2014-08-11 13:10:38 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
// Stack is a base structure for LIFO
|
|
|
|
type Stack struct {
|
|
|
|
sp *StackItem
|
|
|
|
depth uint64
|
2014-08-11 13:10:38 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
// Initialzes new Stack
|
|
|
|
func New() *Stack {
|
|
|
|
var stack *Stack = new(Stack)
|
2014-08-11 13:10:38 +00:00
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
stack.depth = 0
|
|
|
|
return stack
|
2014-08-11 13:10:38 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
// Pushes a given item into Stack
|
|
|
|
func (stack *Stack) Push(item interface{}) {
|
|
|
|
stack.sp = &StackItem{item: item, next: stack.sp}
|
|
|
|
stack.depth++
|
2017-02-20 11:18:03 +00:00
|
|
|
}
|
2014-08-11 13:10:38 +00:00
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
// Deletes top of a stack and return it
|
|
|
|
func (stack *Stack) Pop() interface{} {
|
|
|
|
if stack.depth > 0 {
|
|
|
|
item := stack.sp.item
|
|
|
|
stack.sp = stack.sp.next
|
|
|
|
stack.depth--
|
|
|
|
return item
|
2017-02-20 11:18:03 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
2017-02-20 11:18:03 +00:00
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
// Returns top of a stack without deletion
|
|
|
|
func (stack *Stack) Peek() interface{} {
|
|
|
|
if stack.depth > 0 {
|
|
|
|
return stack.sp.item
|
2017-02-20 11:18:03 +00:00
|
|
|
}
|
|
|
|
|
2017-02-20 18:35:56 +00:00
|
|
|
return nil
|
2014-08-11 13:10:38 +00:00
|
|
|
}
|