Medium
hasNext()很容易出錯伤极,基本上這道題flatten的操作都是在hasNext()這里完成的蛹找。我們peek()一下去看下一個要從stack里取出來的是integer還是list. 如果是integer, 那么ok沒問題hasNext()return true, 而且next()直接return stack.pop.getInteger()就沒事; 如果是list,說明這一坨需要flatten. 那么我們先把這一坨pop()出來哨坪,再從后到前遍歷這個list加到stack里庸疾。到這里發(fā)現(xiàn)我們這樣做不能循環(huán)call下去,只是把list轉(zhuǎn)了個方向往stack里加了一下当编。所以我們要寫一個while loop, 知道能flatten出一個integer為止届慈;
比如[1,2,[3,[4]]]這個NestedList, 一開始我們加到stack里面是[[3,[4]], 2, 1], 然后我們call hasNext()的時候忿偷, stack.peek() = 1金顿, 是integer, 所以直接返回true; 然后我們pop()掉1, call掉next()之后我們stack變成[[3,[4]], 2];這時候再call hasNext(), stack.peek()會得到2鲤桥, ok沒問題跟1時的操作類似揍拆,最后返回true, call一下next()我們再次得到stack = [[3,[4]]], 這這時候call hasNext()的時候就會導(dǎo)致stack.pop(), 然后得到一個list = [3,[4]], 從后到前push到stack里得到[[4], 3],peek()一下得到3是integer所以返回true.再call next()使得3被pop()出來茶凳,stack里面還剩[[4]], 這時候call peek得到的是list, 所以會pop出來得到list = [4], 這時候把4加到stack里面,得到stack = [4](which is different from stack = [[4]]),所以再call hasNext()的時候會檢測到ni.isInteger()然后直接返回true.
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class NestedIterator implements Iterator<Integer> {
Stack<NestedInteger> stack = new Stack<>();
public NestedIterator(List<NestedInteger> nestedList) {
for(int i = nestedList.size() - 1; i >= 0; i--){
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return stack.pop().getInteger();
}
@Override
public boolean hasNext() {
while (!stack.isEmpty()){
NestedInteger ni = stack.peek();
if (ni.isInteger()){
return true;
}
stack.pop();
List<NestedInteger> list = ni.getList();
for(int i = list.size() - 1; i >= 0; i--){
stack.push(list.get(i));
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/