-
Notifications
You must be signed in to change notification settings - Fork 24
/
lib.rs
99 lines (92 loc) · 2.37 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* @lc app=leetcode.cn id=225 lang=rust
*
* [225] 用队列实现栈
*/
// @lc code=start
use std::collections::VecDeque;
#[derive(Debug)]
struct MyStack {
queue1: VecDeque<i32>,
queue2: VecDeque<i32>,
len: i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyStack {
/** Initialize your data structure here. */
fn new() -> Self {
MyStack {
queue1: VecDeque::new(),
queue2: VecDeque::new(),
len: 0,
}
}
/** Push element x onto stack. */
fn push(&mut self, x: i32) {
self.len = self.len + 1;
let (_, not_empty_queue) = self.get_queue();
not_empty_queue.push_back(x);
}
/** Removes the element on top of the stack and returns that element. */
fn pop(&mut self) -> i32 {
self.len = self.len - 1;
let (empty_queue, not_empty_queue) = self.get_queue();
while not_empty_queue.len() != 1 {
let node = not_empty_queue.pop_front().unwrap();
empty_queue.push_back(node)
}
return not_empty_queue.pop_front().unwrap();
}
/** Get the top element. */
fn top(&mut self) -> i32 {
let (_, not_empty_queue) = self.get_queue();
return not_empty_queue[not_empty_queue.len() - 1];
}
/** Returns whether the stack is empty. */
fn empty(&self) -> bool {
self.len == 0
}
fn get_queue(&mut self) -> (&mut VecDeque<i32>, &mut VecDeque<i32>) {
let not_empty_queue;
let empty_queue;
if self.queue1.len() == 0 {
not_empty_queue = &mut self.queue2;
empty_queue = &mut self.queue1
} else {
not_empty_queue = &mut self.queue1;
empty_queue = &mut self.queue2
}
(empty_queue, not_empty_queue)
}
}
// /**
// * Your MyStack object will be instantiated and called as such:
// * let obj = MyStack::new();
// * obj.push(x);
// * let ret_2: i32 = obj.pop();
// * let ret_3: i32 = obj.top();
// * let ret_4: bool = obj.empty();
// */
// @lc code=end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tests() {
let mut queue = MyStack::new();
queue.push(1);
queue.push(2);
// println!("{:?}", queue);
// queue.push(3);
// queue.push(4);
println!("{:?}", queue.pop());
// queue.push(5);
println!("{:?}", queue.top());
// println!("{:?}", queue.pop());
// println!("{:?}", queue.pop());
// println!("{:?}", queue.pop());
}
}