1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * stack.rs
 * Defines a class that represents a stack
 * Created by Andrew Davis
 * Created on 1/15/2019
 * Licensed under the Lesser GNU Public License, version 3
 */

//use statements
use std::collections::LinkedList;

/// A FIFO data structure
pub struct Stack<T> {
    /// The elements that make up the Stack 
    elems: LinkedList<T>,
}

//structure implementation
impl<T> Stack<T> {
    /// Returns a new Stack object
    pub fn new() -> Self {
        return Stack {
            elems: LinkedList::new()
        };
    }

    /// Pushes a value onto the Stack
    ///
    /// # Arguments
    ///
    /// * `value` - The value to push onto the Stack 
    pub fn push(&mut self, value: T) {
        self.elems.push_back(value); 
    }

    /// Pops a value off the Stack and returns it as an Option
    pub fn pop(&mut self) -> Option<T> {
        return self.elems.pop_back();
    }

    /// Returns an immutable reference to the value on top of the Stack
    pub fn peek(&self) -> Option<&T> {
        return self.elems.back();
    }

    /// Returns a mutable reference to the value on top of the Stack
    pub fn peek_mut(&mut self) -> Option<&mut T> {
        return self.elems.back_mut();
    }

    /// Returns the number of items on the Stack
    pub fn size(&self) -> usize {
        return self.elems.len();
    }

    /// Returns whether the Stack is empty
    pub fn is_empty(&self) -> bool {
        return self.elems.is_empty();
    }

    /// Clears the Stack
    pub fn clear(&mut self) {
        self.elems.clear();
    }
}

//end of file