diff --git a/src/problem/mod.rs b/src/problem/mod.rs index d7e6b45..bbf71e3 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -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; \ No newline at end of file +mod p225_implement_stack_using_queues; +mod p232_implement_queue_using_stacks; \ No newline at end of file diff --git a/src/problem/p232_implement_queue_using_stacks.rs b/src/problem/p232_implement_queue_using_stacks.rs new file mode 100644 index 0000000..85f1136 --- /dev/null +++ b/src/problem/p232_implement_queue_using_stacks.rs @@ -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, + out_stack: VecDeque +} + + +/** + * `&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()); + } +}