My code:
/**
* // 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<Iterator<NestedInteger>> st = new Stack<>();
NestedInteger next;
public NestedIterator(List<NestedInteger> nestedList) {
st.push(nestedList.iterator());
}
@Override
public Integer next() {
return next == null ? null : next.getInteger();
}
@Override
public boolean hasNext() {
while (!st.isEmpty()) {
if (!st.peek().hasNext()) {
st.pop();
}
else {
next = st.peek().next();
if (next.isInteger()) {
return true;
}
else {
st.push(next.getList().iterator());
}
}
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
這道題目沒能自己做出來。
看了答案后感覺也很難想到。只不過真的很巧妙。
reference:
https://discuss.leetcode.com/topic/44983/share-my-java-neat-solution-8ms
我一直在想,如果list里面還有list,還有list,還有list,一層層迭代進去,what will happen and what can we do?
我本來是想寫一個dfs函數,但好像每次輸出之后,原狀態很難保存下來。這導致的問題是,下一次輸出需要依靠這個原狀態,如果原狀態無法保存,那么下一次也無法輸出。
這是 stateful api
we need to store the previous state to get the next state
然后答案里面用到了兩個數據結構:
Stack + Iterator
這是第一次我見他們聯合使用。
將iterator壓入棧中,需要拿下一個元素的時候,就看棧頂的iterator
如果他的 hasNext() 返回false,那么先把他彈出。
如果不是,就取出next元素。
如果是integer,直接返回。
如果不是,那么將他的iterator 再次壓入棧中。然后繼續循環。
直到找到某個integer或者將棧中所有的iterator全部遍歷完,最后返回false
原狀態的保存,全部由iterator做到了,我們也不需要再去考慮什么了。
解法很巧妙。
Anyway, Good luck, Richardo! -- 09/06/2016