
Data Structure

This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.
 Illustration of FIFO behavior
Task

Implement a FIFO queue.

Elements are added at one side and popped from the other in the order of insertion.



Operations:

   push   (aka enqueue)    - add element
   pop     (aka dequeue)    - pop first element
   empty                             - return truth value when empty


Errors:

   handle the error of trying to pop from an empty queue (behavior depends on the language and platform)


See

   Queue/Usage   for the built-in FIFO or queue of your language or standard library.


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


 
/* To push a node onto the end of the queue. */
push: procedure (tail);
   declare tail handle (node), t handle (node);
   t = new(:node:);
   get (t => value);
   if tail ^= bind(:null, node:) then
      tail => link = t;
      /* If the queue was non-empty, points the tail of the queue */
      /* to the new node. */
   tail = t; /* Point "tail" at the end of the queue. */
   tail => link = bind(:node, null:);
end push;
 
/* To pop a node from the head of the queue. */
pop: procedure (head, val);
   declare head handle (node), val fixed binary;
   if head = bind(:node, null:) then signal error;
   val = head => value;
   head = head => pointer; /* pops the top node. */
   if head = bind(:node, null:) then tail = head;
      /* (If the queue is now empty, make tail null also.) */
end pop;
 
/* Queue status: the EMPTY function, returns true for empty queue. */
empty: procedure (h) returns (bit(1));
   declare h handle (Node);
   return (h = bind(:Node, null:) );
end empty;
 