Skip to content

Instantly share code, notes, and snippets.

@sychonet
Last active June 9, 2022 11:04
Show Gist options
  • Save sychonet/cc9f7fde18fae4be2dcf4463c0361b30 to your computer and use it in GitHub Desktop.
Save sychonet/cc9f7fde18fae4be2dcf4463c0361b30 to your computer and use it in GitHub Desktop.
A very basic implementation of queue in Golang
// Basic implementation for queue
package main
import "fmt"
type queue struct {
data []int
head int
}
// enqueue inserts an element into the queue and returns true if the operation is successful.
func (q *queue) enqueue(x int) bool {
q.data = append(q.data, x)
return true
}
// dequeue deletes an element from the queue and returns true if the operation is successful.
func (q *queue) dequeue() bool {
if q.isEmpty() {
return false
}
q.head++
return true
}
// front gets the front item from the queue
func (q *queue) front() int {
return q.data[q.head]
}
// isEmpty checks if the queue is empty
func (q *queue) isEmpty() bool {
if q.head >= len(q.data) {
return true
}
return false
}
func main() {
var q queue
q.enqueue(5)
q.enqueue(3)
if !q.isEmpty() {
fmt.Println(q.front())
}
fmt.Println(q.dequeue())
if !q.isEmpty() {
fmt.Println(q.front())
}
fmt.Println(q.dequeue())
if !q.isEmpty() {
fmt.Println(q.front())
}
fmt.Println(q.dequeue())
}
@sychonet
Copy link
Author

sychonet commented Jun 9, 2022

Check the implementation at https://go.dev/play/p/JOTgS8skoEv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment