forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0155-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
typeMinStackstruct {
top*StackNode
minint
}
typeStackNodestruct {
dataint
next*StackNode
lastminint
}
varmystackMinStack=MinStack{top: nil}
varnewtop*StackNode
funcConstructor() MinStack {
returnmystack
}
func (this*MinStack) Push(valint) {
ifthis.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
ifthis.top.data<this.min {
this.min=this.top.data
}
}
func (this*MinStack) Pop() {
ifthis.top.next==nil {
this.top=nil
return
}
this.min=this.top.lastmin
*this.top=*this.top.next
}
func (this*MinStack) Top() int {
returnthis.top.data
}
func (this*MinStack) GetMin() int {
returnthis.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();
*/