Rust Program to Implement the queue data structure


Implement the queue data structure

Rust Programming Language


Implement the queue data structure


Problem


Rust program that implements a queue data structure using a Vec.

Input


struct Queue<T> {
    items: Vec<T>,
}

impl<T> Queue<T> {
    fn new() -> Queue<T> {
        Queue { items: Vec::new() }
    }

    fn enqueue(&mut self, item: T) {
        self.items.push(item);
    }

    fn dequeue(&mut self) -> Option<T> {
        if self.items.is_empty() {
            None
        } else {
            Some(self.items.remove(0))
        }
    }

    fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    fn size(&self) -> usize {
        self.items.len()
    }
}

fn main() {
    let mut q = Queue::new();

    q.enqueue("hello");
    q.enqueue("world");

    println!("Queue size: {}", q.size());

    while let Some(item) = q.dequeue() {
        println!("Dequeued item: {}", item);
    }
}{codeBox}

Output


Queue size: 2
Dequeued item: hello
Dequeued item: world{codeBox}

Explanation


In this program, we define a generic Queue struct that contains a Vec of items. We then define several methods on the Queue struct:

  • new(): creates a new, empty queue.
  • enqueue(): adds an item to the end of the queue.
  • dequeue(): removes and returns the first item in the queue, or returns None if the queue is empty.
  • is_empty(): returns true if the queue is empty, false otherwise.
  • size(): returns the number of items in the queue.

In the main() function, we create a new queue, enqueue two items, print the queue's size to the console, and then dequeue and print each item in the queue.

This is because we first enqueue two strings, "hello" and "world", and then print the size of the queue, which is 2. We then dequeue each item from the queue and print it to the console. Since the queue is a first-in, first-out data structure, the items are dequeued in the same order they were enqueued: "hello" first, followed by "world".


Post a Comment