-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem043.go
More file actions
64 lines (55 loc) · 1.48 KB
/
Copy pathproblem043.go
File metadata and controls
64 lines (55 loc) · 1.48 KB
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
61
62
63
64
package problem043
type stack struct {
values []int
maxValueStack *stack
}
type StackEmptyError struct{}
func (stackEmptyError StackEmptyError) Error() string {
return "StackEmptyError"
}
func NewStack(initialCapacity uint) *stack {
return &stack{
values: make([]int, 0, initialCapacity),
maxValueStack: &stack{
values: make([]int, 0, initialCapacity),
maxValueStack: nil,
},
}
}
func (thisStack *stack) peek() (int, error) {
if len(thisStack.values) == 0 {
return 0, StackEmptyError{}
}
return thisStack.values[len(thisStack.values)-1], nil
}
func (thisStack *stack) Push(value int) *stack {
if thisStack.maxValueStack != nil {
currentMaxValue, err := thisStack.maxValueStack.peek()
if (err != nil && err.Error() == "StackEmptyError") || currentMaxValue <= value {
thisStack.maxValueStack.Push(value)
}
}
thisStack.values = append(thisStack.values, value)
return thisStack
}
func (thisStack *stack) Pop() (int, error) {
if len(thisStack.values) == 0 {
return 0, StackEmptyError{}
}
value := thisStack.values[len(thisStack.values)-1]
thisStack.values = thisStack.values[:len(thisStack.values)-1]
if thisStack.maxValueStack != nil {
currentMaxValue, _ := thisStack.maxValueStack.peek()
if currentMaxValue == value {
_, _ = thisStack.maxValueStack.Pop()
}
}
return value, nil
}
func (thisStack *stack) Max() (int, error) {
currentMaxValue, err := thisStack.maxValueStack.peek()
if err != nil {
return 0, err
}
return currentMaxValue, nil
}