Queue

1.Introduction

  • Add the end of queue and remove elements from the beginning of the queue (First In First Out)

  • Enqueue: Adding a new element to the end of the queue

  • Dequeue: Removing an element from the beginning of a queue

  • Peek

  • Offer: Adding to a queue if space is available

2.The complexity

  • Enqueue, dequeue, isEmpty, isFull: O(1)

  • space complexity: O(N)

3.Where can stacks be used

  • Customer service hotline, calls are assigned to representatives in the order that they are received

  • Queueing jobs to be printed

  • Any order processing systems like in e-commerce websites or bank transaction systems

4.Implement a queue using two stacks

Forward stack

  • Use a forward stack used to push the enqueue elements

    • Enqueue operations are always performed on the forward stack

  • Enqueue requires moving all elements to the forward stack and pushing the last element in I.E. the top

Reverse stack

  • The reverse stack holds the elements in reverse order from the forward stack

    • Dequeue operations are always performed on the reverse stack

  • Dequeue requires moving all elements to the reverse track and popping the last element in I.E. the top

Performance and complexity

  • All enqueues and then dequeues ate O(1) - if only one of these operations are performed

  • O(m)

5.The circular queue

Last updated