Use Iterator to answer Iterator Questions


  • 0
    public class NestedIterator implements Iterator<Integer> {
        private Integer top = null;
        private Stack<Iterator<NestedInteger>> stack = new Stack<>();
        public NestedIterator(List<NestedInteger> nestedList) {
            stack.push(nestedList.iterator());
        }
    
        @Override
        public Integer next() {
            if (top != null) {
                Integer res = top;
                top = null;
                return res;
            }
            else {
                return null;
            }
        }
    
        @Override
        public boolean hasNext() {
            if (top != null) {
                return true;
            }
            while (!stack.isEmpty()) {
                Iterator<NestedInteger> iter = stack.peek();
                if (iter.hasNext()) {
                    NestedInteger ni = iter.next();
                    if (ni.isInteger()) {
                        top = ni.getInteger();
                        return true;
                    }
                    else {
                        stack.push(ni.getList().iterator());
                    }
                }
                else stack.pop(); // 栈顶的iterator已经结束
            }
            return false;
        }
    }
    

Log in to reply
 

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