In: Computer Science
For this exercise, you will be defining a function which USES both the Stack and the Queue ADTs. Your code can make use of any of the Queue ADT methods: Queue(), enqueue(), dequeue(), peek(), size() and is_empty() and any of the Stack ADT methods: Stack(), push(), pop(), peek(), size() and is_empty().
Write a function called mirror_queue(a_queue) which takes a
Queue as a parameter. The function must modify the parameter Queue
object so that the original queue items appear in their original
order followed by a copy of the queue items in reverse
order.
Note: you can assume that the parameter is not empty.
HINT: It will be useful to make use of a Stack and another Queue to help you mirror the elements in the queue.
For example:
Test | Result |
---|---|
q1 = Queue() q1.enqueue(1) q1.enqueue(2) q1.enqueue(3) print(q1) mirror_queue(q1) print(q1) |
Queue: [1, 2, 3] Queue: [1, 2, 3, 3, 2, 1] |
q1 = Queue() q1.enqueue(1) q1.enqueue(2) q1.enqueue(3) q1.enqueue(4) q1.enqueue(5) print(q1) mirror_queue(q1) print(q1) |
Queue: [1, 2, 3, 4, 5] Queue: [1, 2, 3, 4, 5, 5, 4, 3, 2, 1] |
please please thumbs up!!!!
hope it will help uh out!!!
Code::
(IN PYTHON PROGRAMMING LANGUAGE)
---------------------------------------------------------------
import copy
class Queue:
def __init__(self):
self.__items = []
def is_empty(self):
return self.__items == []
def enqueue(self, item):
self.__items.insert(0,item)
def dequeue(self):
if self.__items == []:
raise IndexError ("The queue is empty!")
return self.__items.pop()
def size(self):
return len(self.__items)
def peek(self):
if self.__items ==[]:
raise IndexError ("The queue is empty!")
return self.__items[len(self.__items)-1]
def __str__(self):
return 'Queue: ' + str(self.__items[::-1])
#Implementation of mirror_queue() method
def mirror_queue(a_queue):
#Declare a stack
stack = []
#Make a deep copy of the orginal queue object
#Deep copy doesnot affect original object if changes made to
copy
temp = copy.deepcopy(a_queue)
#Insert values of queue to stack
for i in range(temp.size()):
stack.append(temp.dequeue())
#Append values from top of stack to original queue object
for i in range(len(stack)):
a_queue.enqueue(stack.pop())
# Test 1
q1 = Queue()
q1.enqueue(1)
q1.enqueue(2)
q1.enqueue(3)
print(q1)
mirror_queue(q1)
print(q1)
#Test 2
q1 = Queue()
q1.enqueue(1)
q1.enqueue(2)
q1.enqueue(3)
q1.enqueue(4)
q1.enqueue(5)
print(q1)
mirror_queue(q1)
print(q1)
print()
---------------------------------------------------------------
output::
NOTE :: PLEASE CHECK THE SCREENSHOT OF THE PROGRAM FOR THE INDENTATION OF ABOVE CODE