forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.rs
41 lines (33 loc) · 811 Bytes
/
Stack.rs
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
struct Stack<T> {
list: Vec<T>
}
impl<T> Stack<T> {
fn new() -> Self {
Stack {
list: Vec::new(),
}
}
// Note that this returns a reference to the value
// This is in contrast to pop which gives ownership of the value
fn top(&self) -> Option<&T> {
self.list.last()
}
fn pop(&mut self) -> Option<T> {
self.list.pop()
}
fn push(&mut self, item: T) {
self.list.push(item);
}
fn size(&self) -> usize {
self.list.len()
}
}
fn main() {
let mut i32stack: Stack<i32> = Stack::new();
i32stack.push(4);
i32stack.push(5);
i32stack.push(6);
println!("{:?}", i32stack.pop().unwrap()); // 6
println!("{:?}", i32stack.size()); // 2
println!("{:?}", i32stack.top().unwrap()); // 5
}