Peeking Iterator

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

  • Time: O(n)
  • Space: O(1)
public class PeekingIterator implements Iterator<Integer> {

    private Integer next = null;
    private Iterator<Integer> it;

    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        this.it = iterator;
        if (this.it.hasNext())
            next = this.it.next();
    }

    // Returns the next element without advancing the iterator.
    public Integer peek() {
        return next; 
    }

    // hasNext() and next() should behave the same as in the Iterator.
    // Override them if needed.
    @Override
    public Integer next() {
        Integer res = next;
        next = it.hasNext() ? it.next() : null;
        return res;
    }

    @Override
    public boolean hasNext() {
        return next != null;
    }
}

results matching ""

    No results matching ""