341. Flatten Nested List Iterator
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 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].
/**
* // 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> {
private Stack<NestedInteger> stack=new Stack<NestedInteger>();
public NestedIterator(List<NestedInteger> nestedList) {
for(int i=nestedList.size()-1;i>=0;i--){//把nestedList的值全部放到栈中,从nestedList的尾部开始压栈
stack.push(nestedList.get(i));
}
}
@Override
public Integer next() {
/*
*刚开始写成
*stack.pop();
*return stack.peek().getInteger();
*发现返回null,因为还没取值就把栈顶元素pop了
*/
Integer i=stack.peek().getInteger();
stack.pop();
return i;
}
@Override
public boolean hasNext() {
/*
*刚开始把while放在了NestedIterator方法中,发现只执行了一次的list重新出栈和压栈,后面的list没有进入while操作
*因为NestedIterator()方法只执行了一次,是构造函数
*/
while(!stack.isEmpty() && !stack.peek().isInteger()){
List<NestedInteger> list1=stack.peek().getList();
stack.pop();
for(int i=list1.size()-1;i>=0;i--){
stack.push(list1.get(i));
}
}
if(!stack.isEmpty()){
return true;
}
return false;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/

本文介绍了一个嵌套整数列表的迭代器实现方法。该迭代器能够将嵌套列表中的所有元素展平,并按顺序返回每个元素。通过示例展示了如何使用此迭代器遍历复杂的嵌套列表。
216

被折叠的 条评论
为什么被折叠?



