Golang queue data structure implementation

package main

import (
	"container/list"
	"errors"
	"fmt"
)

// Queue is a list data structure that follows First-In-First-Out (FIFO) methodology
type Queue struct {
	size  int       // size of the queue
	items list.List // holds the elements
}

// enqueue() method inserts new element at the back of the queue
func (queue *Queue) enqueue(str string) (bool, error) {
	if queue.items.Len() >= queue.size {
		return false, errors.New("Overflow")
	}
	queue.items.PushBack(str)
	return true, nil
}

// dequeue() method removes element at the front of the queue
func (queue *Queue) dequeue() (string, error) {
	if queue.items.Len() == 0 {
		return "", errors.New("Empty")
	}
	ret := queue.items.Front().Value.(string)
	queue.items.Remove(queue.items.Front())
	return ret, nil
}

func main() {
	queue := &Queue{size: 5}

	fmt.Println(queue.enqueue("1"))
	fmt.Println(queue.dequeue())
	fmt.Println(queue.dequeue())

	fmt.Println(queue.enqueue("1"))
	fmt.Println(queue.enqueue("2"))
	fmt.Println(queue.enqueue("3"))
	fmt.Println(queue.enqueue("4"))
	fmt.Println(queue.enqueue("5"))
	fmt.Println(queue.enqueue("6"))
}

Leave a Reply