I am required to write a function mirrored(q) to modify a queue so that it mirrors the queue in Python using stacks? For eg calling the function on the queue [1,2,3,4] would produce [1,2,3,4,4,3,2,1].
I know how to reverse the Queue using a stack but don’t know how I can modify q to produce the whole mirrored queue (original order and reversed order) and not just [4,3,2,1]
This is where I got so far:
def mirrored(q):
s = q.size()
stack= Stack()
for i in range(0,s):
front=q.dequeue()
stack.push(front)
for i in range(0,s):
ele=stack.pop()
q.enqueue(ele)
Queue concatenations are not possible so I don’t know how to implement adding of the original queue and reversed queue. Can someone please suggest a fix for my code? I have been cracking my head for really long but for the life of me cannot figure out what the problem is. I understand that when I am doing q.dequeue() the original elements are getting removed. Please help!
>Solution :
You should also add the elements from the original queue to a second queue so you can keep a copy of the original ordering of the data.
def mirrored(q):
s = q.size()
stack= Stack()
backup_q = Queue()
for i in range(0,s):
front=q.dequeue()
stack.push(front)
backup_q.enqueue(front)
for i in range(s):
q.enqueue(backup_q.dequeue())
for i in range(0,s):
ele=stack.pop()
q.enqueue(ele)