Java solution by using two additional variables


  • 1
    A
    Iterator<Integer> iterator;
    int peek_element;
    boolean peek_flag;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.iterator = iterator;
        this.peek_flag = false;
    }
    
    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if (!peek_flag) {
            peek_element = iterator.next();
            peek_flag = true;
        }
        return peek_element;
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if (peek_flag) {
            peek_flag = false;
            return peek_element;
        }
        return iterator.next();
    }
    
    @Override
    public boolean hasNext() {
        return iterator.hasNext() || peek_flag;
    }

Log in to reply
 

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