A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner . In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
In the context of queues, we use the term ENQUEUE for insert and DEQUEUE for delete. Enqueue operation adds an element to the tail of the queue. Dequeue operation removes an element from the head of the queue.
def enqueue(queue, value):
queue.append(value)
def dequeue(queue):
return queue.pop(0)
>>> my_queue = []
>>> enqueue(my_queue, ‘a')
>>> enqueue(my_queue, ‘b')
>>> enqueue(my_queue, ‘c')
>>> my_queue
[‘a’, ‘b’, ‘c’]
>>> dequeue(my_queue)
‘a’
>>> dequeue(my_queue)
‘b’
Let us start with the implementation of Enqueue and Dequeue functions. The enqueue function should append the given value to the tail of the queue. In out implementation here, the enqueue function takes the queue and the value to be inserted as input parameters. The append method available for list data structure is used to insert the value at the tail of the queue. The dequeue function should remove the first element in the queue. In this implementation, the function takes the queue as input parameter. The pop built-in method available for list data structure is used to remove the first element of the list. To remove the first element, the pop method should be called with parameter 0 to specify index 0. The removed value is returned by the function. Since Python list has built-in methods to remove from the head and append to the tail, we do not need separate pointers to the head and tail of the queue.
Then create an empty list that is going to be our queue. In the sample code given above, the list is named ‘my_queue’.
To insert ‘a’, we call the enqueue function with ‘my_queue’ and ‘a’ as input parameters. It will insert ‘a’ at index 0 of the list. Next, we call the enqueue function with ‘b’ as an input parameter. ‘b’ will be inserted at index 1 of the list. Similarly, we insert ‘c’ at index 2 of the list.
To confirm our insertions, we can simply print the queue. You can see in the example that the values have been inserted correctly.
To delete a value from our queue, we call the dequeue function we implemented with ‘my_queue’ as the input parameter. As shown here, it returns ‘a’, which is the first element we inserted.
When we call dequeue again, it returns ‘b’ which is the next element we inserted.