-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem053.go
62 lines (52 loc) · 1.24 KB
/
problem053.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
61
62
package problem053
type stack struct {
capacity int
data []int
}
func newStack(capacity int) *stack {
return &stack{
capacity: capacity,
data: make([]int, 0, capacity),
}
}
func (thisStack *stack) isEmpty() bool {
return len(thisStack.data) == 0
}
func (thisStack *stack) push(v int) *stack {
if len(thisStack.data) >= thisStack.capacity {
panic("max length exceeded")
}
thisStack.data = append(thisStack.data, v)
return thisStack
}
func (thisStack *stack) pop() int {
if len(thisStack.data) == 0 {
panic("stack empty")
}
v := thisStack.data[len(thisStack.data)-1]
thisStack.data = thisStack.data[:len(thisStack.data)-1]
return v
}
type queue struct {
incomingStack *stack
outgoingStack *stack
}
func NewQueue(capacity int) *queue {
return &queue{
incomingStack: newStack(capacity),
outgoingStack: newStack(capacity),
}
}
func (thisQueue *queue) Enqueue(v int) *queue {
for !thisQueue.outgoingStack.isEmpty() {
thisQueue.incomingStack.push(thisQueue.outgoingStack.pop())
}
thisQueue.incomingStack.push(v)
return thisQueue
}
func (thisQueue *queue) Dequeue() int {
for !thisQueue.incomingStack.isEmpty() {
thisQueue.outgoingStack.push(thisQueue.incomingStack.pop())
}
return thisQueue.outgoingStack.pop()
}