232. Implement Queue using Stacks

Since Queue is FIFO but Stack is FILO. If we need to use Stack to implement a Queue, we need to use at least two Stacks. So we use one stack which only handle Push operations, and another Stack which only handle Pop/Peek operations. And we move elements from the Pop only Stack to the other one when Pop/Peek get called. It will reverse the FILO stack elements sequence after that. So we get a FIFO sequence.

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
type Stack []int

func (s *Stack)Empty() bool {
return len(*s) == 0
}

func (s *Stack)Push(x int) {
*s = append(*s, x)
}

func (s *Stack)Pop() int {
var ret int
if !s.Empty() {
lastIndex := len(*s) - 1
ret = (*s)[lastIndex]
*s = (*s)[:lastIndex]
}
return ret
}

func (s *Stack)Peek() int {
var ret int
if !s.Empty() {
ret = (*s)[len(*s) - 1]
}
return ret
}

type MyQueue struct {
m, n *Stack
}

func Constructor() MyQueue {
return MyQueue{
&Stack{},
&Stack{},
}
}

func (q *MyQueue)Push(x int) {
q.m.Push(x)
}

func (q *MyQueue)Pop() int {
q.Peek()
return q.n.Pop()
}

func (q *MyQueue)Peek() int {
if q.n.Empty() {
for !q.m.Empty() {
q.n.Push(q.m.Pop())
}
}
return q.n.Peek()
}


func (q *MyQueue)Empty() bool {
return q.m.Empty() && q.n.Empty()
}