瀏覽代碼

feat: min_stack

Zhang Li 11 月之前
父節點
當前提交
286c947da4
共有 1 個文件被更改,包括 39 次插入0 次删除
  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
+    }
+}