Python mirror queue and reverse queue 1. Write a function, mirror_queue(q) , whi
ID: 3719092 • Letter: P
Question
Python mirror queue and reverse queue
1.
Write a function, mirror_queue(q), which takes a Queue, q, as a parameter and modifies the queue so that the queue items appear in their original order followed by a copy of the queue items in reverse order. You must make use of a stack to help you to solve this problem.
The implementations of both the Stack and Queue ADTs are provided to you. You can simply use: push(), pop(), is_empty() as well as enqueue() and dequeue() as necessary in your function definition.
However, you will need to use the following statement to create a Stack (in this question)
Similarly, you will need to use the following statement to create a Queue (in this question)
For example:
2.
Write a function, reverse_queue(q), which takes a Queue, q, as a parameter and modifies the queue so that the elements in the queue are rearranged into reverse order. You must make use of a stack to help you in reversing the elements in the queue.
The implementations of both the Stack and Queue ADTs are provided to you. You can simply use: push(), pop(), is_empty() as well as enqueue() and dequeue() as necessary in your function definition.
However, you will need to use the following statement to create a Stack (in this question)
Similarly, you will need to use the following statement to create a Queue (in this question)
For example:
Test Resultq1 = my_queue_module.Queue() q1.enqueue(1) q1.enqueue(2) q1.enqueue(3) mirror_queue(q1) print(q1)
Queue: [1, 2, 3, 3, 2, 1]
q1 = my_queue_module.Queue() mirror_queue(q1) print(q1)
Queue: []
Explanation / Answer
def mirror_queue(q):
s = my_stack_module.Stack()
q1 = my_queue_module.Queue()
while (!q.is_empty()):
a = q.dequeue()
q1.enqueue(a)
s.push(a)
while !q1.is_empty():
a = q1.dequeue()
q.enqueue(a)
while !s.is_empty():
a = s.pop()
q.enqueue(a)
return q
def reverse_queue(q):
s = my_stack_module.Stack()
while !q.is_empty():
a = q.dequeue()
s.push(a)
while !s.is_empty():
a = s.pop()
q.enqueue(a)
return q
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.