Given an Iterator class interface with methods:next()andhasNext(), design and implement a PeekingIterator that support thepeek()operation -- it essentially peek() at the element that will be returned by the next call to next().

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {

    private Iterator<Integer> iterator;
    private Integer peeked;

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.iterator = iterator;
        peeked = null;
    }

    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        if(peeked != null)
            return peeked;

        peeked = iterator.next();
        return peeked;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        if(peeked == null) {
            return iterator.next();
        } else {
            int res = peeked;
            peeked = null;
            return res;
        }
    }

    @Override
    public boolean hasNext() {
        if(peeked != null)
            return true;
        return iterator.hasNext();
    }
}

results matching ""

    No results matching ""