20240304 Finished

This commit is contained in:
jackfiled 2024-03-04 10:59:17 +08:00
parent d71c48ea85
commit 2b83455ec0
2 changed files with 86 additions and 1 deletions

View File

@ -62,4 +62,5 @@ mod p2673_make_costs_of_paths_equal_in_a_binary_tree;
mod p2581_count_number_of_possible_root_nodes;
mod p2369_check_if_there_is_a_valid_partition_for_the_array;
mod p2368_reachable_nodes_with_restrictions;
mod p225_implement_stack_using_queues;
mod p225_implement_stack_using_queues;
mod p232_implement_queue_using_stacks;

View File

@ -0,0 +1,84 @@
/**
* [232] Implement Queue using Stacks
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
struct MyQueue {
in_stack: VecDeque<i32>,
out_stack: VecDeque<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 {
MyQueue {
in_stack: VecDeque::new(),
out_stack: VecDeque::new()
}
}
fn push(&mut self, x: i32) {
self.in_stack.push_back(x);
}
fn pop(&mut self) -> i32 {
if self.out_stack.is_empty() {
while let Some(top) = self.in_stack.pop_back() {
self.out_stack.push_back(top);
}
}
self.out_stack.pop_back().unwrap()
}
fn peek(&mut self) -> i32 {
if self.out_stack.is_empty() {
while let Some(top) = self.in_stack.pop_back() {
self.out_stack.push_back(top);
}
}
*self.out_stack.back().unwrap()
}
fn empty(&self) -> bool {
self.out_stack.is_empty() && self.in_stack.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();
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_232() {
let mut queue = MyQueue::new();
queue.push(1);
queue.push(2);
assert_eq!(1, queue.peek());
assert_eq!(1, queue.pop());
assert!(!queue.empty());
}
}