forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deque.rs
62 lines (52 loc) · 1.19 KB
/
deque.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#[derive(Debug)]
struct Deque<T> {
deque: Vec<T>,
}
impl<T> Deque<T> {
fn new() -> Self {
Deque { deque: Vec::new() }
}
fn add_last(&mut self, item: T) {
self.deque.push(item)
}
fn remove_last(&mut self) -> Option<T> {
self.deque.pop()
}
fn add_first(&mut self, item: T) {
self.deque.insert(0, item)
}
fn remove_first(&mut self) -> T {
self.deque.remove(0)
}
fn length(&self) -> usize {
self.deque.len()
}
fn is_empty(&self) -> bool {
self.deque.is_empty()
}
fn peek(&self) -> Option<&T> {
self.deque.first()
}
fn peek_last(&self) -> Option<&T> {
self.deque.last()
}
}
fn main() {
let mut deque: Deque<i32> = Deque::<i32>::new();
deque.add_first(1);
deque.add_last(2);
deque.add_first(3);
println!("{:?}", deque);
deque.remove_last();
deque.remove_first();
println!("{:?}", deque);
println!(
"length: {:?}, is empty? {:?}",
deque.length(),
deque.is_empty()
);
deque.add_first(1);
deque.add_last(2);
deque.add_first(3);
println!("{:?}, {:?}", deque.peek(), deque.peek_last());
}