Created
March 31, 2020 04:17
-
-
Save eikaas/77656ae36a66bd1c367fe3f910909aa4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package zek | |
import "sync" | |
// Stack is a simple stack for arbitrary types. | |
type Stack struct { | |
sync.Mutex | |
v []interface{} | |
} | |
// Len returns number of items on the stack. | |
func (s *Stack) Len() int { | |
s.Lock() | |
defer s.Unlock() | |
return len(s.v) | |
} | |
// Put item onto stack. | |
func (s *Stack) Put(item interface{}) { | |
s.Lock() | |
defer s.Unlock() | |
s.v = append(s.v, item) | |
} | |
// Peek returns the top element without removing it. Panic it stack is empty. | |
func (s *Stack) Peek() interface{} { | |
s.Lock() | |
defer s.Unlock() | |
if len(s.v) == 0 { | |
panic("peek at empty stack") | |
} | |
return s.v[len(s.v)-1] | |
} | |
// Pop item from stack. It's a panic if stack is empty. | |
func (s *Stack) Pop() interface{} { | |
s.Lock() | |
defer s.Unlock() | |
if len(s.v) == 0 { | |
panic("pop from empty stack") | |
} | |
last := len(s.v) - 1 | |
v := s.v[last] | |
s.v = s.v[0:last] | |
return v | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment