Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a function to modify a Queue to show both the original and reversed items in the queue using Stacks

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading