Created
December 4, 2023 16:17
-
-
Save Philogy/5b9d6add3ef201bcaee8f8f4c37a2fde to your computer and use it in GitHub Desktop.
LeetCode: Queue from 2-Stacks in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MyQueue { | |
queue: Vec<i32>, | |
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 { | |
queue: Vec::new(), | |
stack: Vec::new(), | |
} | |
} | |
fn push(&mut self, x: i32) { | |
self.stack.push(x); | |
} | |
fn pop(&mut self) -> i32 { | |
if let Some(x) = self.queue.pop() { | |
return x; | |
} | |
self.rebalance(); | |
self.queue.pop().unwrap() | |
} | |
fn peek(&mut self) -> i32 { | |
if let Some(x) = self.queue.last() { | |
return *x; | |
} | |
self.rebalance(); | |
*self.queue.last().unwrap() | |
} | |
fn empty(&self) -> bool { | |
self.queue.is_empty() && self.stack.is_empty() | |
} | |
fn rebalance(&mut self) { | |
while let Some(x) = self.stack.pop() { | |
self.queue.push(x); | |
} | |
} | |
} | |
fn main() { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment