Queue

Info

The queue is an ordered container of data that enforces a FIFO (first in, first out) policy on adds and removes.

Think of it like a queue (line) for a restaurant. First person in line will get their order first, last person in line will get their order last.

Specification

Definition

For a queue holding data type T:

  • init: (no input) -> Stack
    • Pre: true
    • Post: returned value is a new, empty queue
  • isEmpty: (no input) -> bool
    • Pre: true
    • Post: return value is the same as length == 0
  • enter: (stack element) -> void
    • Pre: true
    • Post: new queue contains
  • leave: (no input) -> void
    • Pre: is not empty
    • Post: new queue contains
  • first: (no input) -> T
    • Pre: is not empty
    • Post: true
  • nuke: (no input) -> void
    • Pre: true
    • Post: all items of the queue have been deleted

Implementation

General Implementation with a Linked List

See Linked List.

Runtimes (see Big O):

General Implementation with a Dynamic Array

See Computer Science/Programming/Arrays

Implementing queue with a dynamic array will either result in huge space complexity or bad runtime complexity due to elements shifting. This implementation will sacrifice space complexity, by using a "first" index that just increments along the array.

Runtimes: