Skip to content

Commit 7954260

Browse files
committed
Create 1381-design-a-stack-with-increment-operation.rs
1 parent 318cce5 commit 7954260

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
struct CustomStack {
2+
mmp: Vec<i32>,
3+
max_size: i32,
4+
}
5+
6+
impl CustomStack {
7+
8+
fn new(max_size: i32) -> Self {
9+
CustomStack {
10+
mmp: vec![],
11+
max_size: max_size,
12+
}
13+
}
14+
15+
fn push(&mut self, x: i32) {
16+
if self.mmp.len() < self.max_size as usize { self.mmp.push(x) }
17+
}
18+
19+
fn pop(&mut self) -> i32 {
20+
let len = self.mmp.len();
21+
if len == 0 { return -1 }
22+
self.mmp.remove(len - 1)
23+
}
24+
25+
fn increment(&mut self, k: i32, val: i32) {
26+
let index = vec![k as usize, self.mmp.len()].into_iter().min().unwrap();
27+
for i in 0..index { self.mmp[i] += val }
28+
}
29+
}
30+
31+
fn main() {
32+
let mut cus_stack = CustomStack::new(3);
33+
cus_stack.push(1);
34+
cus_stack.push(2);
35+
cus_stack.pop();
36+
cus_stack.push(2);
37+
cus_stack.push(3);
38+
cus_stack.push(4);
39+
cus_stack.increment(5, 100);
40+
cus_stack.increment(2, 100);
41+
cus_stack.pop();
42+
cus_stack.pop();
43+
cus_stack.pop();
44+
cus_stack.pop();
45+
}

0 commit comments

Comments
 (0)