|
@@ -0,0 +1,95 @@
|
|
|
|
+package main
|
|
|
|
+
|
|
|
|
+import (
|
|
|
|
+ "bufio"
|
|
|
|
+ "fmt"
|
|
|
|
+ "os"
|
|
|
|
+ "strconv"
|
|
|
|
+ "strings"
|
|
|
|
+)
|
|
|
|
+
|
|
|
|
+/*
|
|
|
|
+1: push 5;push 2;push 1;push 3;push 0;min;top;pop;pop;pop;pop
|
|
|
|
+2:
|
|
|
|
+*/
|
|
|
|
+func main() {
|
|
|
|
+ var minStack = Constructor()
|
|
|
|
+ input := bufio.NewScanner(os.Stdin)
|
|
|
|
+ for input.Scan() {
|
|
|
|
+ line := input.Text()
|
|
|
|
+ if strings.HasPrefix(line, "push ") {
|
|
|
|
+ var digitStr = line[5:]
|
|
|
|
+ var digit, _ = strconv.Atoi(digitStr)
|
|
|
|
+ minStack.Push(digit)
|
|
|
|
+ continue
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if strings.HasPrefix(line, "pop") {
|
|
|
|
+ minStack.Pop()
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if strings.HasPrefix(line, "min") {
|
|
|
|
+ fmt.Println(minStack.Min())
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ if strings.HasPrefix(line, "top") {
|
|
|
|
+ fmt.Println(minStack.Top())
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ fmt.Println(minStack.Stack1, "--------", minStack.Stack2)
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+type MinStack struct {
|
|
|
|
+ Stack1 []int
|
|
|
|
+ Stack2 []int
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+/** initialize your data structure here. */
|
|
|
|
+func Constructor() MinStack {
|
|
|
|
+ return MinStack{}
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (this *MinStack) Push(x int) {
|
|
|
|
+ this.Stack1 = append(this.Stack1, x)
|
|
|
|
+ var length = len(this.Stack2)
|
|
|
|
+ if length == 0 {
|
|
|
|
+ this.Stack2 = append(this.Stack2, x)
|
|
|
|
+ return
|
|
|
|
+ }
|
|
|
|
+ if this.Stack2[length-1] >= x {
|
|
|
|
+ this.Stack2 = append(this.Stack2, x)
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (this *MinStack) Pop() {
|
|
|
|
+ var length = len(this.Stack1)
|
|
|
|
+ if length == 0 {
|
|
|
|
+ return
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ var value = this.Stack1[length-1]
|
|
|
|
+ this.Stack1 = this.Stack1[0 : length-1]
|
|
|
|
+
|
|
|
|
+ var stack2Length = len(this.Stack2)
|
|
|
|
+ if this.Stack2[stack2Length-1] == value {
|
|
|
|
+ this.Stack2 = this.Stack2[0 : stack2Length-1]
|
|
|
|
+ }
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (this *MinStack) Top() int {
|
|
|
|
+ var length = len(this.Stack1)
|
|
|
|
+ if length == 0 {
|
|
|
|
+ return -1
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ return this.Stack1[length-1]
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (this *MinStack) Min() int {
|
|
|
|
+ var length = len(this.Stack2)
|
|
|
|
+ if length == 0 {
|
|
|
|
+ return -1
|
|
|
|
+ }
|
|
|
|
+ return this.Stack2[length-1]
|
|
|
|
+}
|