TutorialEdge

Challenge 06 - Implementing a Queue

Welcome, everyone to the discussion thread for the 6th Go challenge posted to the site :tada:

Feel free to show us how you solved the challenge by posting your solutions below!

Solution:

package main

import (
	"errors"
	"fmt"
)

type Queue struct {
	Items []Flight
}

type Flight struct {
	Origin      string
	Destination string
	Price       int
}

func (q *Queue) Pop() (Flight, error) {
	if q.IsEmpty() {
		return Flight{}, errors.New("Queue is Empty")
	} else {
		firstElemIndex := 0
		var flight Flight
		flight, q.Items = q.Items[firstElemIndex], q.Items[1:]
		return flight, nil
	}
}

func (q *Queue) Push(flight Flight) {
	q.Items = append(q.Items, flight)
}

func (q *Queue) Peek() (Flight, error) {
	if q.IsEmpty() {
		return Flight{}, errors.New("Queue is Empty")
	} else {
		return q.Items[0], nil
	}
}

func (q *Queue) IsEmpty() bool {
	if len(q.Items) == 0 {
		return true
	}
	return false
}

func main() {
	fmt.Println("Go Queue Implementation")
}