|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +#------------------------------------------------------------------------------- |
| 4 | +# """ |
| 5 | +# This is the interface that allows for creating nested lists. |
| 6 | +# You should not implement it, or speculate about its implementation |
| 7 | +# """ |
| 8 | +#class NestedInteger(object): |
| 9 | +# def isInteger(self): |
| 10 | +# """ |
| 11 | +# @return True if this NestedInteger holds a single integer, rather than a nested list. |
| 12 | +# :rtype bool |
| 13 | +# """ |
| 14 | +# |
| 15 | +# def getInteger(self): |
| 16 | +# """ |
| 17 | +# @return the single integer that this NestedInteger holds, if it holds a single integer |
| 18 | +# Return None if this NestedInteger holds a nested list |
| 19 | +# :rtype int |
| 20 | +# """ |
| 21 | +# |
| 22 | +# def getList(self): |
| 23 | +# """ |
| 24 | +# @return the nested list that this NestedInteger holds, if it holds a nested list |
| 25 | +# Return None if this NestedInteger holds a single integer |
| 26 | +# :rtype List[NestedInteger] |
| 27 | +# """ |
| 28 | + |
| 29 | +class NestedIterator(object): |
| 30 | + |
| 31 | + def __init__(self, nestedList): |
| 32 | + """ |
| 33 | + Initialize your data structure here. |
| 34 | + :type nestedList: List[NestedInteger] |
| 35 | + """ |
| 36 | + self.flatlist = [] |
| 37 | + self.idx = 0 |
| 38 | + self.addLists(nestedList) |
| 39 | + |
| 40 | + |
| 41 | + def next(self): |
| 42 | + """ |
| 43 | + :rtype: int |
| 44 | + """ |
| 45 | + if self.hasNext: |
| 46 | + self.idx += 1 |
| 47 | + return self.flatlist[self.idx-1] |
| 48 | + |
| 49 | + def hasNext(self): |
| 50 | + """ |
| 51 | + :rtype: bool |
| 52 | + """ |
| 53 | + return self.idx < len(self.flatlist) |
| 54 | + |
| 55 | + def addLists(self, nest): |
| 56 | + for element in nest: |
| 57 | + if not element.isInteger(): |
| 58 | + self.addLists(element.getList()) |
| 59 | + else: |
| 60 | + self.flatlist.append(element.getInteger()) |
| 61 | + |
| 62 | + |
| 63 | +# Your NestedIterator object will be instantiated and called as such: |
| 64 | +# i, v = NestedIterator(nestedList), [] |
| 65 | +# while i.hasNext(): v.append(i.next()) |
| 66 | +#------------------------------------------------------------------------------- |
0 commit comments