
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


// version 1.1.2
 
import java.util.LinkedList
 
class Queue<E> {
    private val data = LinkedList<E>()
 
    val size get() = data.size
 
    val empty get() = size == 0
 
    fun push(element: E) = data.add(element)
 
    fun pop(): E {
        if (empty) throw RuntimeException("Can't pop elements from an empty queue")
        return data.removeFirst()
    }
 
   val top: E
        get() {
            if (empty) throw RuntimeException("Empty queue can't have a top element")
            return data.first()
        }
 
    fun clear() = data.clear()
 
    override fun toString() = data.toString()
}
 
fun main(args: Array<String>) {
    val q = Queue<Int>()
    (1..5).forEach { q.push(it) }
    println(q)
    println("Size of queue = ${q.size}")
    print("Popping: ")
    (1..3).forEach { print("${q.pop()} ") }
    println("\nRemaining in queue: $q")
    println("Top element is now ${q.top}")
    q.clear()
    println("After clearing, queue is ${if(q.empty) "empty" else "not empty"}")
    try {
        q.pop()
    }
    catch (e: Exception) {
        println(e.message)
    }
}