forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
48 lines (41 loc) · 998 Bytes
/
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
use std::collections::VecDeque;
struct MyQueue {
stk1: Vec<i32>,
stk2: Vec<i32>,
}
impl MyQueue {
fn new() -> Self {
MyQueue {
stk1: Vec::new(),
stk2: Vec::new(),
}
}
fn push(&mut self, x: i32) {
self.stk1.push(x);
}
fn pop(&mut self) -> i32 {
self.move_elements();
self.stk2.pop().unwrap()
}
fn peek(&mut self) -> i32 {
self.move_elements();
*self.stk2.last().unwrap()
}
fn empty(&self) -> bool {
self.stk1.is_empty() && self.stk2.is_empty()
}
fn move_elements(&mut self) {
if self.stk2.is_empty() {
while let Some(element) = self.stk1.pop() {
self.stk2.push(element);
}
}
}
}/**
* 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();
*/