AdSense

Sunday, October 9, 2016

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

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].
Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.
Hint:
  1. Think of "looking ahead". You want to cache the next element.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek() before next() vs next() before peek().
  4. For a clean implementation, check out Google's guava library source code.
Follow up: How would you extend your design to be generic and work with all types, not just integer?

The idea comes from Google's Guava library (it's a quite good library). If the iterator is initialized by the list, we can just use a pointer to get the next element. However, the question asks us to initialize with the iterator. Based on the hint (and Guava), we can use a pointer to track the peeked element. When peek() is called, the iterator still calls next() method to get us the element, but we use a pointer peekedElement to record this element, next time if we call next(), we can just return the element. Note we need another boolean variable isPeeked because peekedElement can be initialized with anything, even one of the elements in the iterator, so we need the flag to distinguish.

For follow up, using Type.


class PeekingIterator implements Iterator {
    Iterator iterator;
    private boolean isPeeked;
    private int peekedElement;
    
 public PeekingIterator(Iterator iterator) {
     if (iterator == null)
         throw new NullPointerException();
     this.iterator = iterator;
     isPeeked = false;
     peekedElement = -1;
 }

    // Returns the next element in the iteration without advancing the iterator.
 public Integer peek() {
        if (isPeeked)
            return peekedElement;
        else {
            if (!hasNext())
                return -1;
            peekedElement = iterator.next();
            isPeeked = true;
            return peekedElement;
        }
 }

 // hasNext() and next() should behave the same as in the Iterator interface.
 // Override them if needed.
 @Override
 public Integer next() {
     if (!isPeeked && hasNext())
         return iterator.next();
     int toReturn = peekedElement;
     peekedElement = -1;
     isPeeked = false;
     return toReturn;
 }

 @Override
 public boolean hasNext() {
     return isPeeked || iterator.hasNext();
 }
}


No comments:

Post a Comment