Rust Program to Implement stack data structure


Implement stack data structure

Rust Programming Language


Implement stack data structure


Problem


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

Input


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

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

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

    fn pop(&mut self) -> Option<T> {
        self.items.pop()
    }

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

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

fn main() {
    let mut stack = Stack::new();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    println!("Stack size: {}", stack.size());

    while let Some(item) = stack.pop() {
        println!("Popped item: {}", item);
    }
}{codeBox}

Output


Stack size: 3
Popped item: 3
Popped item: 2
Popped item: 1{codeBox}

Explanation


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

new(): creates a new, empty stack.
push(): adds an item to the top of the stack.
pop(): removes and returns the top item from the stack, or returns None if the stack is empty.
is_empty(): returns true if the stack is empty, false otherwise.
size(): returns the number of items in the stack.

In the main() function, we create a new stack, push three integers onto the stack, print the stack's size to the console, and then pop and print each item from the stack. Since a stack is a last-in, first-out (LIFO) data structure, the items are popped from the stack in reverse order from which they were pushed: 3 first, followed by 2 and 1.

This is because we first push three integers, 1, 2, and 3, onto the stack, and then print the size of the stack, which is 3. We then pop each item from the stack and print it to the console. Since the stack is a last-in, first-out data structure, the items are popped from the stack in reverse order from which they were pushed: 3 first, followed by 2 and 1.

Post a Comment