-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueue.rs
More file actions
64 lines (58 loc) · 1.72 KB
/
queue.rs
File metadata and controls
64 lines (58 loc) · 1.72 KB
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
//! # Queues
//!
//! To run/test, please run the following commands in your terminal
//!
//! ```sh
//! cargo run --bin queue
//! ```
//!
//! ```sh
//! cargo test --bin queue
//! ```
//!
//! Queues are data types that follows First In First Out principle. The item
//! first added to the queue should be the item that gets out of the queue.
//!
//! We can take an analogy of a ticket counter as a queue where the person with
//! the first token will be the first in the queue.
//!
//! In this example, we are creating a custom structure `Queue` that stores
//! items of the queue in a vector.
//!
//! The queue contains methods `enqueue` and `dequeue` methods to add and remove
//! items from the queue. The item first added to the queue will be removed from
//! the queue first.
struct Queue<T> {
content: Vec<T>, // container for items to store in the stack
}
impl<T> Queue<T> {
fn new() -> Self {
Self {
content: Vec::new(),
}
}
fn enqueue(&mut self, item: T) {
self.content.push(item)
}
fn dequeue(&mut self) -> T {
return self.content.remove(0);
}
fn length(&self) -> usize {
return self.content.len();
}
}
/// To run / test, please run the following command in your terminal:
/// * cargo run --bin queue
/// * cargo test --bin queue
///
fn main() {
let mut queue: Queue<usize> = Queue::new();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
println!("Length of the queue: {}", queue.length()); // 0
println!("first item: {}", queue.dequeue()); // 10
println!("first item: {}", queue.dequeue()); // 20
println!("first item: {}", queue.dequeue()); // 30
println!("Length of the queue: {}", queue.length()); // 0
}