Created
November 3, 2018 04:12
-
-
Save derianpt/93cbf64a759f037ad8bcf8c52664ce79 to your computer and use it in GitHub Desktop.
LIFO Stack and FIFO Queue implementation in Go/Golang.
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 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