Skip to content

feat: add rust solution to lcof problem: No.09 #669

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions lcof/面试题09. 用两个栈实现队列/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,53 @@ class CQueue {
*/
```

### **Rust**

```rust
struct CQueue {
s1: Vec<i32>,
s2: Vec<i32>
}


/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl CQueue {

fn new() -> Self {
CQueue {
s1: Vec::new(),
s2: Vec::new(),
}
}

fn append_tail(&mut self, value: i32) {
self.s1.push(value);
}

fn delete_head(&mut self) -> i32 {
match self.s2.pop() {
Some(value) => value,
None => {
while !self.s1.is_empty() {
self.s2.push(self.s1.pop().unwrap());
}
self.s2.pop().unwrap_or(-1)
}
}
}
}

/**
* Your CQueue object will be instantiated and called as such:
* let obj = CQueue::new();
* obj.append_tail(value);
* let ret_2: i32 = obj.delete_head();
*/
```

### **...**

```
Expand Down
42 changes: 42 additions & 0 deletions lcof/面试题09. 用两个栈实现队列/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
struct CQueue {
s1: Vec<i32>,
s2: Vec<i32>
}


/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl CQueue {

fn new() -> Self {
CQueue {
s1: Vec::new(),
s2: Vec::new(),
}
}

fn append_tail(&mut self, value: i32) {
self.s1.push(value);
}

fn delete_head(&mut self) -> i32 {
match self.s2.pop() {
Some(value) => value,
None => {
while !self.s1.is_empty() {
self.s2.push(self.s1.pop().unwrap());
}
self.s2.pop().unwrap_or(-1)
}
}
}
}

/**
* Your CQueue object will be instantiated and called as such:
* let obj = CQueue::new();
* obj.append_tail(value);
* let ret_2: i32 = obj.delete_head();
*/