How to implement a stack using vector in Rust

2 Answers

0 votes
fn main() {
    let mut stack: Vec<i32> = Vec::new();

    // Push elements onto the stack
    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.push(40);
    
    // Peeking at the Top
    if let Some(top) = stack.last() {
        println!("Top of stack: {}", top);
    }

    // Pop elements off the stack
    while let Some(top) = stack.pop() {
        println!("Popped: {}", top);
    }
}

    
/*
run:

Top of stack: 40
Popped: 40
Popped: 30
Popped: 20
Popped: 10
   
*/
  


answered Aug 15, 2025 by avibootz
0 votes
struct Stack<T> {
    items: Vec<T>,
}

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

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

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

    fn peek(&self) -> Option<&T> {
        self.items.last()
    }

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

fn main() {
    let mut stack = Stack::new();
    stack.push("Rust");
    stack.push("C");
    stack.push("C++");
    stack.push("Java");
    stack.push("Python");

    // Peek at the top element
    if let Some(top) = stack.peek() {
        println!("Top of stack: {}", top);
    }
    
    println!();
    println!("{}", stack.is_empty());
    println!();

    // Pop all elements until the stack is empty
    while !stack.is_empty() {
        if let Some(word) = stack.pop() {
            println!("{}", word);
        }
    }
}


    
/*
run:

Top of stack: Python

false

Python
Java
C++
C
Rust
   
*/

 



answered Aug 15, 2025 by avibootz
...