-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.go
86 lines (70 loc) · 1.42 KB
/
solution.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
)
type stack []int
func (stk *stack) Len() int {
return len(*stk)
}
func (stk *stack) Empty() bool {
return len(*stk) == 0
}
func (stk *stack) Push(num int) {
*stk = append(*stk, num)
}
func (stk *stack) Pop() int {
num := (*stk)[len(*stk)-1]
*stk = (*stk)[:len(*stk)-1]
return num
}
func (stk *stack) Peek() int {
return (*stk)[len(*stk)-1]
}
// MyQueue contains two stacks
type MyQueue struct {
PushStack *stack
PopStack *stack
}
// Constructor initializes MyQueue
func Constructor() MyQueue {
return MyQueue{
PushStack: new(stack),
PopStack: new(stack),
}
}
// Push element x to the back of queue.
func (q *MyQueue) Push(x int) {
q.PushStack.Push(x)
}
// Pop the element from in front of queue and returns that element.
func (q *MyQueue) Pop() int {
if q.PopStack.Empty() {
for q.PushStack.Len() > 0 {
q.PopStack.Push(q.PushStack.Pop())
}
return q.PopStack.Pop()
}
return q.PopStack.Pop()
}
// Peek returns the front element.
func (q *MyQueue) Peek() int {
if q.PopStack.Empty() {
for q.PushStack.Len() > 0 {
q.PopStack.Push(q.PushStack.Pop())
}
return q.PopStack.Peek()
}
return q.PopStack.Peek()
}
// Empty returns whether the queue is empty.
func (q *MyQueue) Empty() bool {
return q.PopStack.Empty() && q.PushStack.Empty()
}
func main() {
obj := Constructor()
obj.Push(1)
popped := obj.Pop()
fmt.Println(popped)
isEmpty := obj.Empty()
fmt.Println(isEmpty)
}