Last updated
Was this helpful?
Last updated
Was this helpful?
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1: Given the list
[[1,1],2,[1,1]]
,By callingnextrepeatedly untilhasNextreturns false, the order of elements returned bynextshould be:
[1,1,2,1,1]
.Example 2: Given the list
[1,[4,[6]]]
,By callingnextrepeatedly untilhasNextreturns false, the order of elements returned bynextshould be:
[1,4,6]
.
实现针对nested的list的iterator,效果和遍历展开了的list一样。处理nested用stack。不过做这题时思路被另一道二维list iterator解法带偏了,总想着要用指针。实际并不需要,倒着把所有元素都压入栈,hasNext遍历栈顶时当遇到nested的元素则把它展开后重新入栈。
每个元素进出一次栈,时空复杂度O(N).
https://leetcode.com/problems/flatten-nested-list-iterator/description/