Queues
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. In a queue, elements are inserted at the rear (enqueue) and removed from the front (dequeue). It operates in a similar way to a queue of people waiting in line for a service.
Below is the Ruby program to implement a queue:
class Queue
def initialize
@elements = []
end
def enqueue(item)
@elements.push(item)
end
def dequeue
@elements.shift
end
def empty?
@elements.empty?
end
end
# Example Usage
queue = Queue.new
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
puts queue.dequeue # Output: 1
puts queue.dequeue # Output: 2
puts queue.empty? # Output: false
puts queue.dequeue # Output: 3
puts queue.empty? # Output: true
Output:
How to Implement Data Structures in Ruby?
Data structures are fundamental components of any programming language, allowing developers to organize and manipulate data efficiently. In Ruby, a versatile and expressive language, implementing various data structures is straightforward. In this article, we’ll explore how to implement common data structures such as arrays, linked lists, stacks, queues, trees, graphs, and hashmaps in Ruby. The article focuses on discussing data structures in Ruby.
Table of Content
- Singly-Linked Lists
- Doubly-Linked Lists
- Circular Linked Lists
- Queues
- Stack
- Hash Tables
- Sets
- Binary Trees
- AVL Trees (Adelson-Velsky and Landis Trees)
- Graphs
- Persistent Lists
Contact Us