-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyQueue.rs
49 lines (40 loc) · 1 KB
/
MyQueue.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
#[derive(Default)]
struct MyQueue {
input: Vec<i32>,
output: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyQueue {
fn new() -> Self {
Default::default()
}
fn push(&mut self, x: i32) {
self.input.push(x);
}
fn pop(&mut self) -> i32 {
self.peek();
self.output.pop().unwrap()
}
fn peek(&mut self) -> i32 {
if self.output.is_empty() {
while !self.input.is_empty() {
self.output.push(self.input.pop().unwrap());
}
}
return *self.output.last().unwrap();
}
fn empty(&self) -> bool {
self.input.is_empty() && self.output.is_empty()
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* let obj = MyQueue::new();
* obj.push(x);
* let ret_2: i32 = obj.pop();
* let ret_3: i32 = obj.peek();
* let ret_4: bool = obj.empty();
*/