341. Flatten Nested List Iterator【M】【42】
2016-05-31 13:26
232 查看
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
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
Example 2:
Given the list
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
Subscribe to see which companies asked this question
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 calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,1,2,1,1].
Example 2:
Given the list
[1,[4,[6]]],
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,4,6].
Subscribe to see which companies asked this question
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): l = nestedList self.res = [] if not l: return while l != []: i = l.pop(0) if i.isInteger(): self.res += i.getInteger(), else: l = i.getList() + l """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ def next(self): return self.res.pop(0) """ :rtype: int """ def hasNext(self): return self.res != [] """ :rtype: bool """ # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
相关文章推荐
- 【题】【差分约束】NKOJ 2457 矩阵问题
- 自定义Dialog
- springMVC每一层的注解
- C++线程安全队列
- iOS杂谈
- startActivityForResult 使用注意事项
- OpenCV区域提取之使用鼠标进行区域提取!
- C++队列模板使用std::queue
- mac 下如何开启 ftp server
- java实现简单的单点登录
- 关于Android的一些资源
- 10、利用Zabbix API创建主机宏
- springMVC事务和仓库注解
- SDK Manager.exe 无法启动,一闪而过的解决办法
- cocos2d-js 自定义监听 EventCustom
- Linux 内核自防护项目 KSPP
- java关键字Static详解
- DHtmlx Gantt - forestme的日志 - 网易博客
- SpringMvc的Url映射和传参案例
- Qt QTableWidget的使用方式