
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


 
 
'==========
Class Queue
'==========
 
 'FIRST IN FIRST OUT
 
bstring buf 'buffer to hold queue content
int    bg   'buffer base offset
int i       'indexer
int le      'length of buffer
 
method constructor()
====================
buf=""
le=0
bg=0
i=0
end method
 
method destructor()
===================
del buf
le=0
bg=0
i=0
end method
 
method Encodelength(int ls)
===========================
int p at (i+strptr buf)
p=ls
i+=sizeof int
end method
 
method push(string s)
=====================
int ls=len s
if i+ls+8>le then
  buf+=nuls 8000+ls*2 'extend buf
  le=len buf
end if
EncodeLength ls 'length of input s
mid buf,i+1,s   'append input s
i+=ls
end method
 
method popLength() as int
=========================
if bg>=i then return -1 'buffer empty
int p at (bg+strptr buf)
bg+=sizeof int
return p
end method
 
method pop(string *s) as int
============================
int ls=popLength
if ls<0 then s="" : return ls 'empty buffer
s=mid buf,bg+1,ls
bg+=ls
'cleanup buffer
if bg>1e6 then
  buf=mid buf,bg+1
  le=len buf 
  i-=bg 'shrink buf
  bg=0
end if
end method
 
method clear()
==============
buf=""
le=0
bg=0
i=0
end method
 
end class 'Queue
 
 
'====
'DEMO
'====
 
new Queue  fifo
string     s
'
fifo.push "HumptyDumpty"
fifo.push "Sat on a wall"
'
int er
do
  er=fifo.pop s
  if er then print "(buffer empty)" : exit do
  print s
loop
 
del fifo
 