Friday, October 6, 2017

284. Peeking Iterator



 80.54 %

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

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

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

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

No comments:

Post a Comment