Skip to content

Commit 937287e

Browse files
committed
add 232
1 parent ed13077 commit 937287e

File tree

1 file changed

+60
-0
lines changed
  • go/232-implement-queue-using-stacks

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package main
2+
3+
type MyQueue struct {
4+
stack1 []int
5+
stack2 []int
6+
}
7+
8+
func Constructor() MyQueue {
9+
return MyQueue{}
10+
}
11+
12+
func (this *MyQueue) Push(x int) {
13+
this.stack1 = append(this.stack1, x)
14+
}
15+
16+
func (this *MyQueue) Pop() int {
17+
if this.Empty() {
18+
return 0
19+
}
20+
if len(this.stack2) > 0 {
21+
pop := this.stack2[len(this.stack2)-1]
22+
this.stack2 = this.stack2[:len(this.stack2)-1]
23+
return pop
24+
} else {
25+
for len(this.stack1) > 0 {
26+
pop := this.stack1[len(this.stack1)-1]
27+
this.stack1 = this.stack1[:len(this.stack1)-1]
28+
this.stack2 = append(this.stack2, pop)
29+
}
30+
pop := this.stack2[len(this.stack2)-1]
31+
this.stack2 = this.stack2[:len(this.stack2)-1]
32+
return pop
33+
}
34+
}
35+
36+
func (this *MyQueue) Peek() int {
37+
if len(this.stack2) > 0 {
38+
return this.stack2[len(this.stack2)-1]
39+
} else {
40+
for len(this.stack1) > 0 {
41+
pop := this.stack1[len(this.stack1)-1]
42+
this.stack1 = this.stack1[:len(this.stack1)-1]
43+
this.stack2 = append(this.stack2, pop)
44+
}
45+
return this.stack2[len(this.stack2)-1]
46+
}
47+
}
48+
49+
func (this *MyQueue) Empty() bool {
50+
return len(this.stack1) == 0 && len(this.stack2) == 0
51+
}
52+
53+
/**
54+
* Your MyQueue object will be instantiated and called as such:
55+
* obj := Constructor();
56+
* obj.Push(x);
57+
* param_2 := obj.Pop();
58+
* param_3 := obj.Peek();
59+
* param_4 := obj.Empty();
60+
*/

0 commit comments

Comments
 (0)