-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0155-min-stack.go
60 lines (48 loc) · 1.04 KB
/
0155-min-stack.go
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
type MinStack struct {
top *StackNode
min int
}
type StackNode struct {
data int
next *StackNode
lastmin int
}
var mystack MinStack = MinStack{top: nil}
var newtop *StackNode
func Constructor() MinStack {
return mystack
}
func (this *MinStack) Push(val int) {
if this.top == nil {
newtop = &StackNode{data: val, next: this.top}
this.min = val
} else {
newtop = &StackNode{data: val, next: this.top, lastmin: this.min}
}
this.top = newtop
if this.top.data < this.min {
this.min = this.top.data
}
}
func (this *MinStack) Pop() {
if this.top.next == nil {
this.top = nil
return
}
this.min = this.top.lastmin
*this.top = *this.top.next
}
func (this *MinStack) Top() int {
return this.top.data
}
func (this *MinStack) GetMin() int {
return this.min;
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(val);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/