54 lines
1.3 KiB
Rust
54 lines
1.3 KiB
Rust
|
#[derive(Default)]
|
||
|
struct MyQueue {
|
||
|
front: Vec<i32>,
|
||
|
back: Vec<i32>
|
||
|
}
|
||
|
|
||
|
// This solution has a maximum complexity of O(n) for
|
||
|
// all the operations combined, but a single operation
|
||
|
// could also be O(n) (apart from push and empty which
|
||
|
// is always O(1))
|
||
|
/**
|
||
|
* `&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 flush(&mut self) {
|
||
|
if self.front.is_empty() {
|
||
|
while let Some(n) = self.back.pop() {
|
||
|
self.front.push(n);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn push(&mut self, x: i32) {
|
||
|
self.back.push(x)
|
||
|
}
|
||
|
|
||
|
fn pop(&mut self) -> i32 {
|
||
|
self.flush();
|
||
|
self.front.pop().unwrap() // Unsafe unwrap because of instructions
|
||
|
}
|
||
|
|
||
|
fn peek(&mut self) -> i32 {
|
||
|
self.flush();
|
||
|
*self.front.last().unwrap() // Unsafe unwrap because of instructions
|
||
|
}
|
||
|
|
||
|
fn empty(&self) -> bool {
|
||
|
self.front.is_empty() && self.back.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();
|
||
|
*/
|