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:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,4,6].
1、队列方式
public class NestedIterator implements Iterator<Integer> {
Queue<Integer> res=new LinkedList<Integer>();
public NestedIterator(List<NestedInteger> nestedList) {
helper(nestedList);
}
public void helper(List<NestedInteger> nestedList) {
for(int i=0;i<nestedList.size();i++){
NestedInteger num=nestedList.get(i);
if(num.isInteger()){
res.offer(num.getInteger());
}else{
helper(num.getList());
}
}
}
@Override
public Integer next() {
return res.poll();
}
@Override
public boolean hasNext() {
if(res.isEmpty())
return false;
else
return true;
}
}
2、堆栈方式
public class NestedIterator implements Iterator<Integer> {
Stack<NestedInteger> res=new Stack<NestedInteger>();
public NestedIterator(List<NestedInteger> nestedList) {
for(int i=nestedList.size()-1;i>=0;i--){
res.push(nestedList.get(i));
}
}
@Override
public Integer next() {
return res.pop().getInteger();
}
@Override
public boolean hasNext() {
while(!res.isEmpty()){
if(res.peek().isInteger())
return true;
else{
List<NestedInteger> list=res.pop().getList();
for(int i=list.size()-1;i>=0;i--){
res.push(list.get(i));
}
}
}
return false;
}
}