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().

思路是在每次取完当前元素后将下一个元素保存,这样peek以及next时可以直接返回这个元素

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

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

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

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

Leave a comment