Simple Java solution using stack 8ms


  • 0
    W
    public class NestedIterator implements Iterator<Integer> {
    
        private Stack<List<NestedInteger>> lstk;
        private List<NestedInteger> curList;
        private Stack<Integer> pstk;
        private int curp;
        public NestedIterator(List<NestedInteger> nestedList) {
            lstk=new Stack<>();
            pstk=new Stack<>();
            curList=nestedList;
            curp=0;
        }
    
        @Override
        public Integer next() {
            NestedInteger e=curList.get(curp);
            curp++;
            return e.getInteger();
        }
    
        @Override
        public boolean hasNext() {
            if(curp<curList.size()) {
                NestedInteger e=curList.get(curp);
                if(e.isInteger()) 
                    return true;
                else {
                    lstk.push(curList);
                    curp++;
                    pstk.push(curp);
                    curList=e.getList();
                    curp=0;
                    return hasNext();
                }
            }
            if(lstk.empty()) return false;
            curList=lstk.pop();
            curp=pstk.pop();
            return hasNext();
        }
    }

  • 0
    H

    Great intuitive solution


Log in to reply
 

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