Initial Commit
This commit is contained in:
64
internal/stack/stack.go
Normal file
64
internal/stack/stack.go
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
AMU: Custom simple markup language
|
||||
Copyright (C) 2021 Arsen Musayelyan
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Package stack implements a simple stack using go slices.
|
||||
package stack
|
||||
|
||||
import "reflect"
|
||||
|
||||
// Stack is a LIFO stack using slices for storage
|
||||
type Stack struct {
|
||||
items []interface{}
|
||||
}
|
||||
|
||||
// Create a new stack
|
||||
func New() *Stack {
|
||||
return &Stack{}
|
||||
}
|
||||
|
||||
// Add a value to the end of the stack
|
||||
func (s *Stack) Push(val interface{}) {
|
||||
// Add element to slice
|
||||
s.items = append(s.items, val)
|
||||
}
|
||||
|
||||
// Remove the value on the end of the stack and return it.
|
||||
func (s *Stack) Pop() interface{} {
|
||||
// Get index of last element
|
||||
n := s.Size() - 1
|
||||
// Get last item in slice
|
||||
item := s.items[n]
|
||||
// Set element to zero value
|
||||
s.items[n] = reflect.Zero(reflect.TypeOf(item)).Interface()
|
||||
// Remove element
|
||||
s.items = s.items[:n]
|
||||
return item
|
||||
}
|
||||
|
||||
// Return value on the end of the stack without removing
|
||||
func (s *Stack) Peek() interface{} {
|
||||
// Get index of last element
|
||||
n := s.Size() - 1
|
||||
// Return last element
|
||||
return s.items[n]
|
||||
}
|
||||
|
||||
// Get the amount of items on the stack
|
||||
func (s *Stack) Size() int {
|
||||
return len(s.items)
|
||||
}
|
||||
Reference in New Issue
Block a user