7ms Iterator Based Solution, anyway to optimize it?


  • 0
    T
    public class NestedIterator implements Iterator<Integer> {
        private Stack<Iterator<NestedInteger>> iterStk;
        private Integer last = null;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            this.iterStk = new Stack<>();
            if (nestedList != null) {
                Iterator<NestedInteger> iter = nestedList.iterator();
                iterStk.push(iter);
            }
        }
    
        @Override
        public Integer next() {
            if (last == null) {
        		throw new RuntimeException("Illegal State");
        	}
            return last;
        }
    
        @Override
        public boolean hasNext() {
            while (!iterStk.isEmpty()) {
                Iterator<NestedInteger> cur = iterStk.peek();
                if (cur.hasNext()) {
                    NestedInteger top = cur.next();
                    if (top.isInteger()) {
                    	last = top.getInteger();
                        return true;
                    } else {
                        iterStk.push(top.getList().iterator());
                    }
                } else {
                    iterStk.pop();
                }
            } 
            return false;
        }
    }
    

    The next() method return different value when called multiple times for a normal Integer iterator. But it will make the code more complex than this one, anyone have better idea on making next() function modify the internal status?


Log in to reply
 

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