Created
April 13, 2021 10:23
-
-
Save vrat28/8e2e40ca9eaeac4dc1ea2971c9fce777 to your computer and use it in GitHub Desktop.
Flatten Nested List Iterator Solution (Swift)
This file contains 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
class NestedIterator { | |
private var list:[Int] | |
private var currentIndex: Int | |
init(_ nestedList: [NestedInteger]) { | |
self.list = [] | |
currentIndex = 0 | |
flatten(nestedList) | |
} | |
func flatten(_ nestedList: [NestedInteger]) { | |
for element in nestedList { | |
print(element) | |
if element.isInteger() { | |
list.append(element.getInteger()) | |
} | |
else{ | |
flatten(element.getList()) | |
} | |
} | |
} | |
func next() -> Int { | |
defer { | |
currentIndex += 1 | |
} | |
return list[currentIndex] | |
} | |
func hasNext() -> Bool { | |
return currentIndex < list.count | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment