Skip to content
Advertisement

printing elements of circular queue in python

I am not understanding what this part of code (to print elements of circular queue) is doing and how?

    elif (self.tail >= self.head):
        for i in range(self.head, self.tail + 1):
            print(self.queue[i], end=" ")
        print()
    else:
        for i in range(self.head, self.k):
            print(self.queue[i], end=" ")
        for i in range(0, self.tail + 1):
            print(self.queue[i], end=" ")
        print()

at function printCQueue . why tail needs to go self.tail +1 , why it goes where head is? , how it doesn’t print same value twice (head)

Full code:

class MyCircularQueue():
    def __init__(self, k):
        self.k = k
        self.queue = [None] * k
        self.head = self.tail = -1

    # Insert an element into the circular queue
    def enqueue(self, data):

        if ((self.tail + 1) % self.k == self.head):
            print("The circular queue is fulln")

        elif (self.head == -1):
            self.head = 0
            self.tail = 0
            self.queue[self.tail] = data
        else:
            self.tail = (self.tail + 1) % self.k
            self.queue[self.tail] = data

    # Delete an element from the circular queue
    def dequeue(self):
        if (self.head == -1):
            print("The circular queue is emptyn")

        elif (self.head == self.tail):
            temp = self.queue[self.head]
            self.head = -1
            self.tail = -1
            return temp
        else:
            temp = self.queue[self.head]
            self.head = (self.head + 1) % self.k
            return temp

    def printCQueue(self):
        if(self.head == -1):
            print("No element in the circular queue")

        elif (self.tail >= self.head):
            for i in range(self.head, self.tail + 1):
                print(self.queue[i], end=" ")
            print()
        else:
            for i in range(self.head, self.k):
                print(self.queue[i], end=" ")
            for i in range(0, self.tail + 1):
                print(self.queue[i], end=" ")
            print()


# Your MyCircularQueue object will be instantiated and called as such:
obj = MyCircularQueue(5)
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
obj.enqueue(4)
obj.enqueue(5)
print("Initial queue")
obj.printCQueue()
    
obj.dequeue()
print("After removing an element from the queue")
obj.printCQueue()

Advertisement

Answer

for range function in python ie range(start, end, step=1) here end part is exclusive. ie it doesn’t count.

example: list(range(1, 5)) will give [1,2,3,4] here ned which is 5 is not included in final list.

So to include self.tail we have to give +1 so. self.tail become inclusive.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement