This program demonstrates the implementation of a queue using an array in Go. The queue supports enqueue, dequeue, peek, and empty operations, functioning as a FIFO (First In First Out) data structure.
Program Code
package main
import (
"fmt"
)
// Queue represents the queue structure
type Queue struct {
items []int
}
// NewQueue creates a new Queue
func NewQueue() *Queue {
return &Queue{items: []int{}}
}
// Enqueue adds an item at the end of the queue
func (q *Queue) Enqueue(item int) {
q.items = append(q.items, item)
}
// Dequeue removes the item at the front of the queue and returns it
func (q *Queue) Dequeue() int {
if len(q.items) == 0 {
fmt.Println("Queue is empty")
return -1 // Assuming -1 is an error value for empty queue
}
item := q.items[0] // get the front item
q.items = q.items[1:] // remove the front item
return item
}
// Peek returns the item at the front of the queue without removing it
func (q *Queue) Peek() int {
if len(q.items) == 0 {
fmt.Println("Queue is empty")
return -1 // Assuming -1 is an error value for empty queue
}
return q.items[0]
}
// IsEmpty returns true if the queue is empty
func (q *Queue) IsEmpty() bool {
return len(q.items) == 0
}
func main() {
q := NewQueue()
q.Enqueue(1)
q.Enqueue(2)
fmt.Println("Peek:", q.Peek()) // Outputs: Peek: 1
fmt.Println("Dequeue:", q.Dequeue()) // Outputs: Dequeue: 1
fmt.Println("Dequeue:", q.Dequeue()) // Outputs: Dequeue: 2
fmt.Println("Is the queue empty?", q.IsEmpty()) // Outputs: Is the queue empty? true
}
Explanation
- Queue Structure: The queue is implemented using a slice to hold the items. The struct
Queue
contains a slice of integers as its underlying storage. - Operations:
Enqueue
adds an item to the end of the queue.Dequeue
removes the item from the front of the queue and returns it. It also handles the case where the queue is empty.Peek
returns the front item without removing it from the queue, also checking if the queue is empty.IsEmpty
checks and returns whether the queue is empty.
Running the Program
To execute this Go program:
- Save the code in a file named
queue.go
. - Open a terminal or command prompt.
- Navigate to the directory where the file is stored.
- Run the program by typing
go run queue.go
.
The output will demonstrate the functionality of the queue, showing the results of enqueues, dequeues, and other operations, validating that the queue performs as expected according to the FIFO principle. Adjust the main
function to test different scenarios and observe the behavior of the queue under various operations.