I am not understanding what this part of code (to print elements of circular queue) is doing and how?
JavaScript
x
11
11
1
elif (self.tail >= self.head):
2
for i in range(self.head, self.tail + 1):
3
print(self.queue[i], end=" ")
4
print()
5
else:
6
for i in range(self.head, self.k):
7
print(self.queue[i], end=" ")
8
for i in range(0, self.tail + 1):
9
print(self.queue[i], end=" ")
10
print()
11
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:
JavaScript
1
66
66
1
class MyCircularQueue():
2
def __init__(self, k):
3
self.k = k
4
self.queue = [None] * k
5
self.head = self.tail = -1
6
7
# Insert an element into the circular queue
8
def enqueue(self, data):
9
10
if ((self.tail + 1) % self.k == self.head):
11
print("The circular queue is fulln")
12
13
elif (self.head == -1):
14
self.head = 0
15
self.tail = 0
16
self.queue[self.tail] = data
17
else:
18
self.tail = (self.tail + 1) % self.k
19
self.queue[self.tail] = data
20
21
# Delete an element from the circular queue
22
def dequeue(self):
23
if (self.head == -1):
24
print("The circular queue is emptyn")
25
26
elif (self.head == self.tail):
27
temp = self.queue[self.head]
28
self.head = -1
29
self.tail = -1
30
return temp
31
else:
32
temp = self.queue[self.head]
33
self.head = (self.head + 1) % self.k
34
return temp
35
36
def printCQueue(self):
37
if(self.head == -1):
38
print("No element in the circular queue")
39
40
elif (self.tail >= self.head):
41
for i in range(self.head, self.tail + 1):
42
print(self.queue[i], end=" ")
43
print()
44
else:
45
for i in range(self.head, self.k):
46
print(self.queue[i], end=" ")
47
for i in range(0, self.tail + 1):
48
print(self.queue[i], end=" ")
49
print()
50
51
52
# Your MyCircularQueue object will be instantiated and called as such:
53
obj = MyCircularQueue(5)
54
obj.enqueue(1)
55
obj.enqueue(2)
56
obj.enqueue(3)
57
obj.enqueue(4)
58
obj.enqueue(5)
59
print("Initial queue")
60
obj.printCQueue()
61
62
obj.dequeue()
63
print("After removing an element from the queue")
64
obj.printCQueue()
65
66
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.