Skip to content

Commit 661f4d7

Browse files
add 341
1 parent 5183eb0 commit 661f4d7

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.github.contest.design
2+
3+
/**
4+
* 341. Flatten Nested List Iterator
5+
* Alternative Solution
6+
*/
7+
8+
class NestedIteratorAlternativeSolution(nestedList: List<NestedInteger>) {
9+
10+
private val stack = ArrayDeque<NestedInteger>().apply {
11+
nestedList.reversed().forEach { addFirst(it) }
12+
}
13+
14+
fun next(): Int {
15+
if (!hasNext()) throw NoSuchElementException()
16+
return stack.removeFirst().getInteger()!!
17+
}
18+
19+
fun hasNext(): Boolean {
20+
while (stack.isNotEmpty()) {
21+
val top = stack.first()
22+
if (top.isInteger()) {
23+
return true
24+
}
25+
stack.removeFirst().getList()?.reversed()?.forEach { stack.addFirst(it) }
26+
}
27+
return false
28+
}
29+
}

contest/src/main/java/com/github/contest/design/DesignLeetcode.kt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,9 @@ class CombinationIterator(characters: String, combinationLength: Int) {
252252
*/
253253

254254
class NestedInteger {
255+
256+
fun isInteger() = true
257+
255258
fun getInteger(): Int? {
256259
return null
257260
}

0 commit comments

Comments
 (0)