Stack

Linked List Implementation

Rust

Java

import java.util.Optional;

public class Stack<T> {
    Node<T> top;

    public void push(T value) {
        top = new Node<T>(value, top);
    }

    public Optional<T> pop() {
        if (top == null)
            return Optional.empty();

        var result = top.value;
        top = top.next;
        return Optional.of(result);
    }
}

Array Implementation

Rust

#![allow(unused)]
fn main() {
pub struct Stack<T> {
    buf: Box<[T]>,
    len: usize,
}

impl<T> From<Vec<T>> for Stack<T> {
    fn from(value: Vec<T>) -> Self {
        Self {
            buf: value.into_boxed_slice(),
            len: 0,
        }
    }
}

impl<T> Stack<T> {
    pub fn len(&self) -> usize {
        self.len
    }

    pub fn push(&mut self, value: T) -> Result<(), &'static str> {
        if self.len == self.buf.len() {
            return Err("Pirla, non hai piu' spazio per i piatti!");
        }

        self.buf[self.len] = value;
        self.len += 1;

        Ok(())
    }

    pub fn pop(&mut self) -> Option<&T> {
        if self.len == 0 {
            return None;
        }

        self.len -= 1;
        self.buf.get(self.len)
    }
}

impl<T: Copy> Iterator for Stack<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.pop().and_then(|&v| Some(v))
    }
}
}

Java

import java.util.Optional;

public class ArrayStack<T> {
    Object[] stack;
    Integer top;

    public ArrayStack(Integer size) {
        stack = new Object[size];
        top = 0;
    }

    public Boolean isFull() {
        return top == stack.length - 1;
    }

    public void push(T value) throws IndexOutOfBoundsException {
        if (isFull())
            throw new IndexOutOfBoundsException();

        stack[top] = value;
        top++;
    }

    public Optional<Object> pop() {
        if (top == 0)
            return Optional.empty();

        var result = stack[top];
        top--;
        return Optional.of(result);
    }