
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


DEFINE MAXSIZE="200"
BYTE ARRAY queue(MAXSIZE)
BYTE queueFront=[0],queueRear=[0]
 
BYTE FUNC IsEmpty()
  IF queueFront=queueRear THEN
    RETURN (1)
  FI
RETURN (0)
 
PROC Push(BYTE v)
  BYTE rear
 
  rear=queueRear+1
  IF rear=MAXSIZE THEN
    rear=0
  FI
  IF rear=queueFront THEN
    PrintE("Error: queue is full!")
    Break()
  FI
  queue(queueRear)=v
  queueRear=rear
RETURN
 
BYTE FUNC Pop()
  BYTE v
 
  IF IsEmpty() THEN
    PrintE("Error: queue is empty!")
    Break()
  FI
  v=queue(queueFront)
  queueFront==+1
  IF queueFront=MAXSIZE THEN
    queueFront=0
  FI
RETURN (v)
 
PROC TestIsEmpty()
  IF IsEmpty() THEN
    PrintE("Queue is empty")
  ELSE
    PrintE("Queue is not empty")
  FI
RETURN
 
PROC TestPush(BYTE v)
  PrintF("Push: %B%E",v)
  Push(v)
RETURN
 
PROC TestPop()
  BYTE v
 
  Print("Pop: ")
  v=Pop()
  PrintBE(v)
RETURN
 
PROC Main()
  TestIsEmpty()
  TestPush(10)
  TestIsEmpty()
  TestPush(31)
  TestPop()
  TestIsEmpty()
  TestPush(5)
  TestPop()
  TestPop()
  TestPop()
RETURN