Queue Data Structure
How Queue Works
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. Elements are added to one end (rear) and removed from the other end (front) of the queue.
Key operations:
- Enqueue: Adds an element to the rear of the queue
- Dequeue: Removes and returns the element from the front of the queue
- Peek: Returns the front element without removing it
Time complexities:
- Enqueue: O(1)
- Dequeue: O(1)
- Peek: O(1)
Queues are used in many applications, including task scheduling in operating systems, breadth-first search in graph algorithms, and handling requests in web servers.
class Queue:
items
function enqueue(element):
items.append(element)
visualize()
function dequeue():
if isEmpty():
return null
element = items.removeFirst()
visualize()
return element
function front():
if isEmpty():
return null
return items[0]
function isEmpty():
return items.length == 0