adt/stack/
stack.rs

1/*
2 * stack.rs
3 * Defines a class that represents a stack
4 * Created by Andrew Davis
5 * Created on 1/15/2019
6 * Licensed under the Lesser GNU Public License, version 3
7 */
8
9//use statements
10use std::collections::LinkedList;
11
12/// A FIFO data structure
13pub struct Stack<T> {
14    /// The elements that make up the Stack 
15    elems: LinkedList<T>,
16}
17
18//structure implementation
19impl<T> Stack<T> {
20    /// Returns a new Stack object
21    pub fn new() -> Self {
22        return Stack {
23            elems: LinkedList::new()
24        };
25    }
26
27    /// Pushes a value onto the Stack
28    ///
29    /// # Arguments
30    ///
31    /// * `value` - The value to push onto the Stack 
32    pub fn push(&mut self, value: T) {
33        self.elems.push_back(value); 
34    }
35
36    /// Pops a value off the Stack and returns it as an Option
37    pub fn pop(&mut self) -> Option<T> {
38        return self.elems.pop_back();
39    }
40
41    /// Returns an immutable reference to the value on top of the Stack
42    pub fn peek(&self) -> Option<&T> {
43        return self.elems.back();
44    }
45
46    /// Returns a mutable reference to the value on top of the Stack
47    pub fn peek_mut(&mut self) -> Option<&mut T> {
48        return self.elems.back_mut();
49    }
50
51    /// Returns the number of items on the Stack
52    pub fn size(&self) -> usize {
53        return self.elems.len();
54    }
55
56    /// Returns whether the Stack is empty
57    pub fn is_empty(&self) -> bool {
58        return self.elems.is_empty();
59    }
60
61    /// Clears the Stack
62    pub fn clear(&mut self) {
63        self.elems.clear();
64    }
65}
66
67//end of file