Skip to content

Instantly share code, notes, and snippets.

@elvisfromsouth
Created April 29, 2024 09:58
Show Gist options
  • Save elvisfromsouth/58c17978ce70ebc15232082135e8fbfa to your computer and use it in GitHub Desktop.
Save elvisfromsouth/58c17978ce70ebc15232082135e8fbfa to your computer and use it in GitHub Desktop.
Iterator Recursion
// написать имплементацию интерфейса Iterator<T>, где Т может быть либо Int, либо Iterator<T>
interface MyIterator<T> {
fun hasNext(): Boolean
fun next(): T
}
class IntRecursionImpl(
items: List<Any>
): MyIterator<Int> {
val items = items.reversed().toMutableList()
var nextItem: Int? = null
override fun hasNext(): Boolean {
val lastItem = items.lastOrNull() ?: return false
if (lastItem is Int) {
nextItem = lastItem
items.removeLast()
return true
}
lastItem as MyIterator<*>
return if (lastItem.hasNext()) {
val next = lastItem.next()
if (next is MyIterator<*>) {
items.add(next)
hasNext()
} else {
nextItem = next as Int
true
}
} else {
items.removeLast()
hasNext()
}
}
override fun next(): Int {
if (nextItem == null) {
hasNext()
}
return nextItem ?: throw IllegalStateException()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment