Queue Implementation in Golang
In this article, we would be discussing the implementation of Queue(backed by Array/Slice) in Golang
This would be a follow-up to my recent article:
Introduction
A queue is an abstract data structure (ADT) that follows a particular order in which the operations are performed.
It follows the First In First Out (LIFO) order for operations.
In a layman example, a queue is any queue of consumers for a resource where the consumer that came first is served first.
The difference between a queue and a stack is the removal order, in a stack, we remove the item the most recently added; in a queue, we remove the item the least recently added.
Representation
We would start by defining the basic building block for our implementation i.e. defining a struct for Queue that would be backed by Array or a slice in golang terminology.
Variables
- Queue: backed by an integer slice which will hold our data.
- Front: Pointing towards the head position of the queue.
- Back: Pointing towards the end position of the queue.
Operations
We would be defining the below operations on our queue for demonstration purposes.
- Add()
- Remove()
- Peek()
- Size()
- Print()
So, let us start with implementing the above-defined methods.
Before we start with the implementation we would be creating a method that would create a new ArrayQueue object which will be utilized by our defined methods.
NewQueue:
This method will create a new instance of our Queue with the initial capacity as a parameter.
Add:
Add method will take in data as a parameter which in our instance would be of type int.
As we know Queue follows FIFO order for insertion and removal of data, thus the data would be added at the front of the queue and will be moved further upon additions of a new element.
We will also be resizing the queue whenever we reach the capacity and the resizing logic will be present in the Add method itself.
Add method can also be referred to as Enqueue.
Remove:
Remove or Dequeue method will return the data from the back of the queue and delete the same from the queue.
While dequeuing, we would be incrementing the front to point to the next element in the queue.
Peek:
Peek is similar to the remove/dequeue method, the only difference between them is that while using Peek we will not the deleting the element from the queue.
Size:
The size of the queue will be calculated by an arithmetic subtraction between the Back location and the Front location of the queue.
Print:
To print all the elements in the queue we would iterate over the queue from location Front -> Back
Now that we have completed our implementation it’s time to test the ArrayQueue
Output:
1 | 2 | 3 |
Size := 3
2 | 3 |
Size := 2
Peek := 2
Size := 2
Conclusion
This brings us to the end of the article. Thank you for your time.
The code in the discussion is available at this link.