Java solution using LinkedList


  • 0
    D
    public class NestedIterator implements Iterator<Integer> {
        LinkedList<NestedInteger> linkedList = new LinkedList<>();
    
        public NestedIterator(List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) {
                linkedList.add(ni);
            }
        }
    
        @Override
        public Integer next() {
            return linkedList.removeFirst().getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while (!linkedList.isEmpty()) {
                NestedInteger ni = linkedList.getFirst();
                if (ni.isInteger()) {
                    return true;
                }
                linkedList.removeFirst();
                List<NestedInteger> list = ni.getList();
                for (int i = list.size() - 1; i >= 0 ; i--) {
                    linkedList.addFirst(list.get(i));
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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