In: Computer Science
what is the solution of this code? Also how would I run it in python to check? q = Queue()
q.enqueue(10)
q.enqueue(12)
q.enqueue(15)
for i in range(len(q)):
→ if len(q) % 2 == 0:
→ → q.enqueue(q.dequeue())
→ else:
→ → q.dequeue()
print(q)
Queue is a datastructure that follows first in first out order insertion or deletions.
q.enque(10) // 10 is added to rear end of the queue. 10
q.enque(12) // 12 is added to rear end of the queue. 10 12
q.enque(15) // 15 is added to rear end of the queue. 10 12 15.
next we have a for loop running upto length of Queue. Here the length of the queue is 3.so for loop runs for 3 times here.
3% 2 ! = 0 , so the else block will execute. Here dequeue(), so 10 will be removed from the queue. So now queue becomes : 12 15
len(q) now becomes 2, and 2%2 == 0, so if block will execute. q.enqueue(q.dequeue()), so q.dequeue returns 12, so 12 will be removed and we are passing 12 to enqueue(), so 12 will be added to the end of the queue. So final queue is: 15 12.
len(q) now is again 2, so if block will again execute, so we dequeue the 15 and add 15 to queue again, so final queue is: 12 15.
so finally printing q will print [ 12 15] to the console.