Queue Implementation in Rust

1. Introduction

A queue is a linear data structure that follows the First In First Out (FIFO) principle. This means the first element added to the queue will be the first element to be removed. It can be visualized as a line of people waiting for their turn; the person who arrives first gets served first.

2. Implementation Steps

1. Define the Queue struct with a Vec to store the queue elements.

2. Implement a new function to initialize the queue.

3. Implement an enqueue function to add an element to the end of the queue.

4. Implement a dequeue function to remove the element from the front of the queue.

5. Implement a peek function to view the front element without removing it.

6. Implement an is_empty function to check if the queue is empty.

3. Implementation in Rust Programming

// Defining the Queue struct
pub struct Queue<T> {
    elements: Vec<T>,
}
impl<T> Queue<T> {
    // Initialize an empty queue
    pub fn new() -> Self {
        Queue {
            elements: Vec::new(),
        }
    }
    // Add an element to the end of the queue
    pub fn enqueue(&mut self, value: T) {
        self.elements.push(value);
    }
    // Remove and return the front element of the queue
    pub fn dequeue(&mut self) -> Option<T> {
        if self.is_empty() {
            None
        } else {
            Some(self.elements.remove(0))
        }
    }
    // View the front element without removing it
    pub fn peek(&self) -> Option<&T> {
        self.elements.first()
    }
    // Check if the queue is empty
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }
}
fn main() {
    let mut queue: Queue<i32> = Queue::new();
    queue.enqueue(5);
    queue.enqueue(10);
    queue.enqueue(15);
    println!("Front of the queue: {:?}", queue.peek());
    println!("Dequeued from queue: {:?}", queue.dequeue());
    println!("Front of the queue after dequeue: {:?}", queue.peek());
    println!("Is the queue empty? {}", queue.is_empty());
}

Output:

Front of the queue: Some(5)
Dequeued from queue: Some(5)
Front of the queue after dequeue: Some(10)
Is the queue empty? false

Explanation:

1. The Queue struct is defined to hold elements using a Vec. The generic type T allows it to store any type of element.

2. The new function initializes an empty queue.

3. The enqueue function adds an element to the end of the queue.

4. The dequeue function removes and returns the front element. If the queue is empty, it returns None.

5. The peek function provides a way to view the front element without removing it. If the queue is empty, it returns None.

6. The is_empty function checks if the queue is empty.

7. The main function demonstrates using the queue by enqueuing elements, peeking at the front element, dequeuing an element, and checking if it's empty.


Comments