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
- Pre:
isEmpty
:(no input) -> bool
- Pre:
true
- Post: return value is the same as
length == 0
- Pre:
enter
:(stack element) -> void
- Pre:
true
- Post: new queue contains
- Pre:
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
- Pre:
Implementation
General Implementation with a Linked List
See Linked List.
init
:- Initialize a first and last node as
nullptr
- Initialize a first and last node as
enter
:- Create a new node and set its value
- If
isEmpty
, set the first and last pointer to this node, else set thenext
field of the last node to the current node, and set thelast
pointer to the new node
isEmpty
:- Check if first node is
nullptr
- Check if first node is
leave
:- Store the address of the first node
- Set the first node the next node
- If the next node is null, set the last pointer to null as well
- Delete the stored address of the first node in (1)
first
- Return the first node
nuke
- Nuke the linked list by deleting each node one by one (could be done by calling leave over and over again)
Runtimes (see Big O):
init
:enter
:isEmpty
:leave
:first
:nuke
:
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.
init
:- Initialize the array
enter
:- Push to the back of the array
isEmpty
:- Check if the length of the array is equal to
firstIndex
- Check if the length of the array is equal to
leave
:- Increment
firstIndex
by 1
- Increment
first
- Return
firstIndex
element of the array
- Return
nuke
- Delete each element of the array if necessary, delete the array if necessary
Runtimes:
init
:enter
:(amortized) isEmpty
:leave
:first
:nuke
: