Java solution using queue


  • 0
    L
    public class NestedIterator implements Iterator<Integer> {
    private Queue<Integer> queue = new LinkedList<>(); 
    public NestedIterator(List<NestedInteger> nestedList) {
        parseList(nestedList);
    }
    private void parseList(List<NestedInteger> nestedList){
        for(NestedInteger ni : nestedList){
            if(ni.isInteger()){
                queue.offer(ni.getInteger());
            }
            else parseList(ni.getList());
        }
    }
    @Override
    public Integer next() {
        return queue.poll();
    }
    
    @Override
    public boolean hasNext() {
        if(queue.isEmpty()) return false;
        return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.