Created
April 29, 2024 09:58
-
-
Save elvisfromsouth/58c17978ce70ebc15232082135e8fbfa to your computer and use it in GitHub Desktop.
Iterator Recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// написать имплементацию интерфейса 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