Merge pull request #1723 from Jack-Zhang-1314/patch-14

update 0232.用栈实现队列.md about rust
This commit is contained in:
程序员Carl
2022-11-09 10:27:25 +08:00
committed by GitHub

View File

@ -622,6 +622,47 @@ class MyQueue() {
}
```
rust:
```rust
struct MyQueue {
stack_in: Vec<i32>,
stack_out: Vec<i32>,
}
impl MyQueue {
fn new() -> Self {
MyQueue {
stack_in: Vec::new(),
stack_out: Vec::new(),
}
}
fn push(&mut self, x: i32) {
self.stack_in.push(x);
}
fn pop(&mut self) -> i32 {
if self.stack_out.is_empty(){
while !self.stack_in.is_empty() {
self.stack_out.push(self.stack_in.pop().unwrap());
}
}
self.stack_out.pop().unwrap()
}
fn peek(&mut self) -> i32 {
let res = self.pop();
self.stack_out.push(res);
res
}
fn empty(&self) -> bool {
self.stack_in.is_empty() && self.stack_out.is_empty()
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>