forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackUsingQueues.kt
73 lines (66 loc) · 1.73 KB
/
StackUsingQueues.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
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
package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import java.util.*
/**
* Implement a last-in-first-out (LIFO) stack using only two queues.
* The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
*
* [Source](https://leetcode.com/problems/implement-stack-using-queues/)
*/
@UseCommentAsDocumentation
class MyStack {
private val queue: Queue<Int> = LinkedList()
private val backup: Queue<Int> = LinkedList()
fun push(x: Int) {
queue.add(x)
}
fun pop(): Int {
val elem: Int
while (true) {
val next = queue.remove()
if (queue.isNotEmpty()) {
// Do not put last element
backup.add(next)
} else {
// record the last element
elem = next
break
}
}
// Offload from [backup] queue
while (backup.isNotEmpty()) {
val next = backup.remove()
queue.add(next)
}
return elem
}
fun top(): Int {
val elem: Int
while (true) {
val next = queue.remove()
backup.add(next) // backup all elements
// Record last element
if (queue.isEmpty()) {
elem = next
break
}
}
while (backup.isNotEmpty()) {
val next = backup.remove()
queue.add(next)
}
return elem
}
fun empty(): Boolean {
return queue.isEmpty()
}
}
fun main() {
val myStack = MyStack()
myStack.push(1)
myStack.push(2)
myStack.top() shouldBe 2
myStack.pop() shouldBe 2
myStack.empty() shouldBe false
}