Skip to content

Instantly share code, notes, and snippets.

@derianpt
Created November 3, 2018 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derianpt/93cbf64a759f037ad8bcf8c52664ce79 to your computer and use it in GitHub Desktop.
Save derianpt/93cbf64a759f037ad8bcf8c52664ce79 to your computer and use it in GitHub Desktop.
LIFO Stack and FIFO Queue implementation in Go/Golang.
package main
import (
"errors"
"fmt"
)
func main() {
// test out queue
var queue Queue
queue.Offer(0)
queue.Offer(1)
queue.Offer(2)
first, _ := queue.Peek()
fmt.Println("head:", first)
polled, _ := queue.Poll()
fmt.Println("polled:", polled)
fmt.Println("final queue:", queue)
// test out stack
var stack Stack
stack.Push(0)
stack.Push(1)
stack.Push(2)
top, _ := stack.Peek()
fmt.Println("top:", top)
popped, _ := stack.Pop()
fmt.Println("popped:", popped)
fmt.Println("final stack:", stack)
}
// Queue is the Go implementation of Queue
type Queue []interface{}
// Offer adds an element to the back of this queue.
func (queue *Queue) Offer(element interface{}) {
*queue = append(*queue, element)
}
// Poll removes the head element of this queue. If queue is empty, it returns
// -1 and an error.
func (queue *Queue) Poll() (interface{}, error) {
if len(*queue) > 0 {
polled := (*queue)[0]
*queue = (*queue)[1:]
return polled, nil
}
return -1, errors.New("queue is empty")
}
// Peek returns the head element of this queue. If queue is empty, it returns
// -1 and an error.
func (queue *Queue) Peek() (interface{}, error) {
if len(*queue) > 0 {
return (*queue)[0], nil
}
return -1, errors.New("queue is empty")
}
// Stack is the Go implementation of stack
type Stack []interface{}
// Push ...
func (s *Stack) Push(element interface{}) {
*s = append(*s, element)
}
// Pop removes the last element of this stack. If stack is empty, it returns
// -1 and an error.
func (s *Stack) Pop() (interface{}, error) {
if len(*s) > 0 {
popped := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return popped, nil
}
return -1, errors.New("stack is empty")
}
// Peek returns the topmost element of the stack. If stack is empty, it returns
// -1 and an error.
func (s *Stack) Peek() (interface{}, error) {
if len(*s) > 0 {
return (*s)[len(*s)-1], nil
}
return -1, errors.New("stack is empty")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment