1. Introduction
A Queue is a linear data structure that follows the First In First Out (FIFO) principle, meaning the first element added to the queue will be the first one to be removed. Primary operations associated with a queue are enqueue, which adds an element to the rear of the queue, and dequeue, which removes the front element.
2. Implementation Steps
1. Define the Queue class and initialize an empty list (or array in Ruby) to store elements.
2. Implement the enqueue method to add an element to the end of the queue.
3. Implement the dequeue method to remove and return the front element from the queue.
4. Implement the peek method to view the front element without removing it.
5. Implement a method to check if the queue is empty.
3. Implementation in Ruby Programming
class Queue
def initialize
@items = [] # Initializing an empty array to store the queue elements
end
# Adding an item to the end of the queue
def enqueue(item)
@items.push(item)
end
# Removing the front item from the queue
def dequeue
@items.shift
end
# Viewing the front item without removing it
def peek
@items.first
end
# Checking if the queue is empty
def is_empty?
@items.empty?
end
end
# Client code
queue = Queue.new
queue.enqueue(5)
queue.enqueue(10)
puts "Front of the queue: #{queue.peek}" # Output: 5
queue.dequeue
puts "Front of the queue after dequeue: #{queue.peek}" # Output: 10
Output:
Front of the queue: 5 Front of the queue after dequeue: 10
Explanation:
1. The Queue class is initialized with an empty array @items that will be used to store the queue's elements.
2. The enqueue method adds an element to the end of the @items array.
3. The dequeue method removes and returns the first element from the @items array.
4. The peek method returns the first element from the @items array without removing it.
5. The is_empty? method checks if the @items array is empty, indicating that the queue is empty.
Comments
Post a Comment