forked from ByteByteGoHq/coding-interview-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementAQueueUsingAStack.kt
41 lines (35 loc) · 1.03 KB
/
ImplementAQueueUsingAStack.kt
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
import java.util.Stack
class Queue {
private val enqueueStack = Stack<Int>()
private val dequeueStack = Stack<Int>()
fun enqueue(x: Int) {
enqueueStack.push(x)
}
private fun transferEnqueueToDequeue() {
// If the dequeue stack is empty, push all elements from the enqueue stack
// onto the dequeue stack. This ensures the top of the dequeue stack
// contains the most recent value.
if (dequeueStack.isEmpty()) {
while (enqueueStack.isNotEmpty()) {
dequeueStack.push(enqueueStack.pop())
}
}
}
fun dequeue(): Int {
transferEnqueueToDequeue()
// Pop and return the value at the top of the dequeue stack.
return if (dequeueStack.isNotEmpty()) {
dequeueStack.pop()
} else {
-1
}
}
fun peek(): Int {
transferEnqueueToDequeue()
return if (dequeueStack.isNotEmpty()) {
dequeueStack.peek()
} else {
-1
}
}
}