Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d62715d

Browse files
authored
Create 0232-implement-queue-using-stacks.kt
1 parent c73e11f commit d62715d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class MyQueue() {
2+
var s1 = LinkedList<Int>()
3+
var s2 = LinkedList<Int>()
4+
5+
fun push(x: Int) {
6+
s1.addLast(x)
7+
}
8+
9+
fun pop(): Int {
10+
if (s2.isEmpty())
11+
refill()
12+
return s2.removeLast() ?: -1
13+
}
14+
15+
fun peek(): Int {
16+
if (s2.isEmpty())
17+
refill()
18+
return s2.peekLast() ?: -1
19+
}
20+
21+
fun empty() = maxOf(s1.size, s2.size) == 0
22+
23+
private fun refill() {
24+
while (s1.isNotEmpty())
25+
s2.addLast(s1.removeLast())
26+
}
27+
28+
}

0 commit comments

Comments
 (0)