Data Structures and Algorithms
Elements A, B and C are added to an empty queue in this order. Then one element is removed, D is added and one is removed, and E is added and one is removed. In what order are the elements removed?
- AA, B, C
- BC, D, E
- CC, B, A
Show answer and explanation
Answer: A. A, B, C
A queue is a first-in, first-out (FIFO) structure: items are removed in the order they were added. After A, B and C are added, the first removal takes A. Even though D and E are added at the back afterward, B and C at the front come out first, so the removal order is A, B, C, and D and E remain. C, D, E is the order you would get from a stack (LIFO), which removes the most recently added item each time. Queues are used for print jobs, for message queues that pass data between tasks, and for breadth-first search.
- A. Correct. B and C, added earlier, come out before D and E.
- B. This is the order for a stack (LIFO), which removes the most recently added item each time.
- C. This is the reverse of the insertion order, not queue order.