Skip to content

Commit 1645b0b

Browse files
committed
problem 053
1 parent 8d37719 commit 1645b0b

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

problem053/README.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
## Daily Coding Problem: Problem #53
2+
3+
4+
Good morning! Here's your coding interview problem for today.
5+
6+
This problem was asked by Apple.
7+
8+
Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it.

problem053/problem053.go

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package problem053
2+
3+
type stack struct {
4+
capacity int
5+
data []int
6+
}
7+
8+
func newStack(capacity int) *stack {
9+
return &stack{
10+
capacity: capacity,
11+
data: make([]int, 0, capacity),
12+
}
13+
}
14+
15+
func (thisStack *stack) isEmpty() bool {
16+
return len(thisStack.data) == 0
17+
}
18+
19+
func (thisStack *stack) push(v int) *stack {
20+
if len(thisStack.data) >= thisStack.capacity {
21+
panic("max length exceeded")
22+
}
23+
thisStack.data = append(thisStack.data, v)
24+
return thisStack
25+
}
26+
27+
func (thisStack *stack) pop() int {
28+
if len(thisStack.data) == 0 {
29+
panic("stack empty")
30+
}
31+
v := thisStack.data[len(thisStack.data)-1]
32+
thisStack.data = thisStack.data[:len(thisStack.data)-1]
33+
return v
34+
}
35+
36+
type queue struct {
37+
incomingStack *stack
38+
outgoingStack *stack
39+
}
40+
41+
func NewQueue(capacity int) *queue {
42+
return &queue{
43+
incomingStack: newStack(capacity),
44+
outgoingStack: newStack(capacity),
45+
}
46+
}
47+
48+
func (thisQueue *queue) Enqueue(v int) *queue {
49+
for !thisQueue.outgoingStack.isEmpty() {
50+
thisQueue.incomingStack.push(thisQueue.outgoingStack.pop())
51+
}
52+
thisQueue.incomingStack.push(v)
53+
return thisQueue
54+
}
55+
56+
func (thisQueue *queue) Dequeue() int {
57+
for !thisQueue.incomingStack.isEmpty() {
58+
thisQueue.outgoingStack.push(thisQueue.incomingStack.pop())
59+
}
60+
return thisQueue.outgoingStack.pop()
61+
62+
}

problem053/problem053_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package problem053
2+
3+
import "testing"
4+
5+
func TestQueue(t *testing.T) {
6+
q := NewQueue(16)
7+
for i := 0; i < 8; i++ {
8+
q.Enqueue(i)
9+
}
10+
11+
for i := 0; i < 8; i++ {
12+
if v := q.Dequeue(); v != i {
13+
t.Logf("%d != %d", v, i)
14+
t.Fail()
15+
}
16+
}
17+
}

0 commit comments

Comments
 (0)