Last active
June 9, 2022 11:04
-
-
Save sychonet/cc9f7fde18fae4be2dcf4463c0361b30 to your computer and use it in GitHub Desktop.
A very basic implementation of queue in 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
// 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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check the implementation at https://go.dev/play/p/JOTgS8skoEv