Java Solution using Queue


  • 0
    T

    Here is my solution, please tell me if there is any improvement I can make.

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

Log in to reply
 

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