Queue Implementation in Python

In this source code example, we will write a code to implement the Queue data structure in Python.

Queue Data Structure

A queue is an ordered list in which insertions are done at one end (rear) and deletions are done at another end (front). The first element to be inserted is the first one to be deleted. Hence, it is called the First in First out (FIFO) or Last in Last out (LILO) list.
A queue is a data structure used for storing data (similar to Linked Lists and Stacks). In a queue, the order in which data arrives is important. In general, a queue is a line of people or things waiting to be served in sequential order starting at the beginning of the line or sequence.
Queue Operations:
When an element is inserted in a queue, the concept is called EnQueue.
When an element is removed from the queue, the concept is called DeQueue.
DeQueueing an empty queue is called underflow (treated as an Exception).
EnQueuing an element in a full queue is called overflow (treat as an Exception).

Queue Implementation in Python

class Queue(object):
    def __init__(self, limit = 10):
        self.queue = []
        self.front = None
        self.rear = None
        self.limit = limit
        self.size = 0

    def __str__(self):
        return ' '.join([str(i) for i in self.queue])

    # to check if queue is empty
    def isEmpty(self):
        return self.size <= 0

    # to add an element from the rear end of the queue
    def enqueue(self, data):
        if self.size >= self.limit:
            return -1          # queue overflow
        else:
            self.queue.append(data)

        # assign the rear as size of the queue and front as 0
        if self.front is None:
            self.front = self.rear = 0
        else:
            self.rear = self.size

        self.size += 1

    # to pop an element from the front end of the queue
    def dequeue(self):
        if self.isEmpty():
            return -1          # queue underflow
        else:
            self.queue.pop(0)
            self.size -= 1
            if self.size == 0:
                self.front = self.rear = 0
            else:
                self.rear = self.size - 1

    def getSize(self):
        return self.size

if __name__ == '__main__':
    myQueue = Queue()
    for i in range(10):
        myQueue.enqueue(i)
    print(myQueue)
    print('Queue Size:',myQueue.getSize())
    myQueue.dequeue()
    print(myQueue)
    print('Queue Size:',myQueue.getSize())

Output:

0 1 2 3 4 5 6 7 8 9
Queue Size: 10
1 2 3 4 5 6 7 8 9
Queue Size: 9

Related Data Structures in Python


Comments