Skip to content

Instantly share code, notes, and snippets.

@Philogy
Created December 4, 2023 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Philogy/5b9d6add3ef201bcaee8f8f4c37a2fde to your computer and use it in GitHub Desktop.
Save Philogy/5b9d6add3ef201bcaee8f8f4c37a2fde to your computer and use it in GitHub Desktop.
LeetCode: Queue from 2-Stacks in Rust
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