Java 7ms solution use queue


  • 0
    S

    use flatNest() method to flat the nest recursively

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

Log in to reply
 

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