Browse Source

feat: min_stack

Zhang Li 11 months ago
parent
commit
286c947da4
1 changed files with 39 additions and 0 deletions
  1. 39 0
      src/solutions/stack/min_stack.rs

+ 39 - 0
src/solutions/stack/min_stack.rs

@@ -0,0 +1,39 @@
+use std::cmp;
+
+struct StackElement {
+    val: i32,
+    min: i32,
+}
+
+struct MinStack {
+    stack: Vec<StackElement>,
+    min: i32,
+}
+
+impl MinStack {
+    fn new() -> Self {
+        MinStack {
+            stack: Vec::new(),
+            min: i32::MAX,
+        }
+    }
+
+    fn push(&mut self, val: i32) {
+        let elem = StackElement {val: val, min: self.min};
+        self.stack.push(elem);
+        self.min = cmp::min(self.min, val);
+    }
+
+    fn pop(&mut self) {
+        let value = self.stack.pop().unwrap();
+        self.min = value.min;
+    }
+
+    fn top(&self) -> i32 {
+        self.stack.last().unwrap().val
+    }
+
+    fn get_min(&self) -> i32 {
+        self.min
+    }
+}