LinkedList is the good choice for java


  • 0
    L
    public class NestedIterator implements Iterator<Integer> {
        LinkedList<Integer> ll = new LinkedList<Integer>();
        
        public NestedIterator(List<NestedInteger> nestedList) {
            flat(nestedList);
        }
        
        void flat(List<NestedInteger> list){
            for (NestedInteger ni : list) {
                if (ni.isInteger()) ll.add(ni.getInteger());
                else flat(ni.getList());
            }
        }
    
        @Override
        public Integer next() {
            if (ll.isEmpty()) return null;
            else return ll.poll();
        }
    
        @Override
        public boolean hasNext() {
            return !ll.isEmpty();
        }
    }
    

Log in to reply
 

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