Write a function called
dequeue_element(queue, i)
that takes a queue called queue and an index of an element in the queue, i. This function should get the element at index i of the queue and dequeue it but leave all of the other elements in the original order. The function should then return the dequeued value
For example, if queue = [A, B, C, D, E, F, G] and the function is called as:
dequeue_element(queue, 2)
Once the function is complete, queue = [A, B, D, E, F, G] and the function returns C. If i is out of range, raise a Exception. To get full credit, this function should not use any additional list-based data structures (stacks, lists, dequeues, strings etc).
in python
CODE :
Explanation is avaliable in the comments
def dequeue_element(queue,index):
queue_len=len(queue) # length of the queue
if index < 0:
raise Exception("Given Index is out of range") # raising exception
if index is out of range.
if index > queue_len:
raise Exception("Given Index is out of range") # raising exception
if index is out of range.
else:
# avoiding slicing solution as it is creating another additonal
list.
# only way is to traverse O(N).
for i in range(0,queue_len): # traversing till the index
found.
if index == i:
break;
queue_element_removed = queue[i] #element which is to be
removed
# relocating elements
for j in range(i+1,queue_len):
queue[j-1]=queue[j]
queue.pop() # removes last element
return queue
queue = ['A', 'B' , 'C', 'D' , 'E', 'F', 'G']
index=2
# Function calling
print(dequeue_element(queue,index))
print(dequeue_element(queue,1))
print(dequeue_element(queue,5))
print(dequeue_element(queue,0))
Output :
Get Answers For Free
Most questions answered within 1 hours.