Skip to content

Instantly share code, notes, and snippets.

@akshanshgusain
Created November 16, 2022 07:28
Show Gist options
  • Save akshanshgusain/0ec6aaec63e6cc3e75321970540a825e to your computer and use it in GitHub Desktop.
Save akshanshgusain/0ec6aaec63e6cc3e75321970540a825e to your computer and use it in GitHub Desktop.
Stack data structure implementation in go
package Stack
import (
"container/list"
"fmt"
)
type Stack struct {
stack *list.List
}
func (s *Stack) Size() int {
return s.stack.Len()
}
func (s *Stack) Empty() bool {
return s.stack.Len() == 0
}
//Push element at the front of the list: O(1)
func (s *Stack) Push(value string) {
s.stack.PushFront(value)
}
//Pop element from the front if the list: O(1)
func (s *Stack) Pop() error {
if s.stack.Len() > 0 {
e := s.stack.Front()
s.stack.Remove(e)
return nil
}
return fmt.Errorf("stack is empty")
}
// Top Get the top element: O(1)
func (s *Stack) Top() (string, error) {
if s.stack.Len() > 0 {
if val, ok := s.stack.Front().Value.(string); ok {
return val, nil
}
return "", fmt.Errorf("stack datatype is incorrect")
}
return "", fmt.Errorf("stack is empty")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment