forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
59 lines (50 loc) · 1.25 KB
/
Solution.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
struct MyQueue {
in_stack: Vec<i32>,
out_stack: 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 {
Self {
in_stack: vec![],
out_stack: vec![],
}
}
fn push(&mut self, x: i32) {
self.in_stack.push(x);
}
fn pop(&mut self) -> i32 {
if self.out_stack.is_empty() {
self.fill_out();
}
self.out_stack.pop().unwrap()
}
fn peek(&mut self) -> i32 {
if self.out_stack.is_empty() {
self.fill_out();
}
*self.out_stack.last().unwrap()
}
fn empty(&self) -> bool {
self.in_stack.is_empty() && self.out_stack.is_empty()
}
fn fill_out(&mut self){
let MyQueue { in_stack, out_stack } = self;
if out_stack.is_empty() {
while !in_stack.is_empty() {
out_stack.push(in_stack.pop().unwrap());
}
}
}
}
/**
* 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();
*/