To implement a queue (First-In-First-Out) using a slice in Go, you can follow these steps:
type Queue struct {
items []int
front int
rear int
}
// Enqueue adds an element to the rear of the queue
func (q *Queue) Enqueue(item int) {
q.items = append(q.items, item)
q.rear++
}
// Dequeue removes and returns the front element of the queue
func (q *Queue) Dequeue() int {
if q.IsEmpty() {
panic("Queue is empty")
}
item := q.items[q.front]
q.items = q.items[q.front+1:]
q.rear--
return item
}
// IsEmpty checks if the queue is empty
func (q *Queue) IsEmpty() bool {
return q.front == q.rear
}
// Size returns the number of elements in the queue
func (q *Queue) Size() int {
return q.rear - q.front
}
// Front returns the front element of the queue without removing it
func (q *Queue) Front() int {
if q.IsEmpty() {
panic("Queue is empty")
}
return q.items[q.front]
}
queue := Queue{}
queue.Enqueue(1)
queue.Enqueue(2)
queue.Enqueue(3)
fmt.Println(queue.Front()) // Output: 1
fmt.Println(queue.Dequeue()) // Output: 1
fmt.Println(queue.Dequeue()) // Output: 2
fmt.Println(queue.Size()) // Output: 1
fmt.Println(queue.IsEmpty()) // Output: false
Now you have successfully implemented a queue (First-In-First-Out) using a slice in Go.