Untitled

 avatar
unknown
plain_text
a year ago
1.9 kB
24
Indexable
use std::fmt;

// Define the Node enum
enum Node {
    Nil,
    Elem(i32, Box<Node>),
}

// Implement display for Node to help printing
impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Node::Nil => write!(f, "Nil"),
            Node::Elem(value, next) => {
                write!(f, "{}-> ", value)?;
                next.fmt(f)
            }
        }
    }
}

// Define the Stack struct
struct Stack {
    top: Node,
}

impl Stack {
    fn new() -> Self {
        Stack { top: Node::Nil }
    }

    fn push(&mut self, value: i32) {
        println!("Pushing {} onto the stack.", value);
        let new_node = Node::Elem(value, Box::new(std::mem::replace(&mut self.top, Node::Nil)));
        self.top = new_node;
    }

    fn pop(&mut self) -> Option<i32> {
        match std::mem::replace(&mut self.top, Node::Nil) {
            Node::Nil => None,
            Node::Elem(value, next) => {
                self.top = *next;
                println!("Popped {} from the stack.", value);
                Some(value)
            }
        }
    }

    fn peek(&self) -> Option<i32> {
        match &self.top {
            Node::Nil => None,
            Node::Elem(value, _) => Some(*value),
        }
    }

    fn is_empty(&self) -> bool {
        matches!(self.top, Node::Nil)
    }

    fn print(&self) {
        println!("Stack contents: {}", self.top);
    }
}

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

    stack.push(10);
    stack.push(20);
    stack.push(30);

    stack.print();
    println!("Top of the stack: {}", stack.peek().unwrap());

    stack.pop();
    stack.print();

    stack.pop();
    stack.print();

    stack.pop();
    stack.print();

    println!("Is the stack empty? {}", stack.is_empty());
}
Editor is loading...
Leave a Comment