@@ -0,0 +1,2006 @@
+import java.util.Iterator;%0A%0A/**%0A * Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that%0A * support the peek() operation -- it essentially peek() at the element that will be returned by the next call to%0A * next().%0A *%0A * Here is an example. Assume that the iterator is initialized to the beginning of the list: %5B1, 2, 3%5D.%0A *%0A * Call next() gets you 1, the first element in the list.%0A *%0A * Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.%0A *%0A * You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.%0A *%0A * Hint:%0A *%0A * Think of %22looking ahead%22. You want to cache the next element. Is one variable sufficient? Why or why not?%0A *%0A * Test your design with call order of peek() before next() vs next() before peek().%0A *%0A * For a clean implementation, check out Google's guava library source code.%0A *%0A * Follow up: How would you extend your design to be generic and work with all types, not just integer?%0A *%0A * Tags: Design%0A *%0A * Similar Problems: (M) Binary Search Tree Iterator, (M) Flatten 2D Vector, (M) Zigzag Iterator%0A */%0Apublic class PeekingIterator implements Iterator%3CInteger%3E %7B%0A%0A    private Integer next;%0A    private Iterator%3CInteger%3E iter;%0A%0A    public PeekingIterator(Iterator%3CInteger%3E iterator) %7B%0A        // initialize any member here.%0A        this.iter = iterator;%0A        if (iterator.hasNext()) %7B%0A            next = iterator.next();%0A        %7D%0A    %7D%0A%0A    // Returns the next element in the iteration without advancing the iterator.%0A    public Integer peek() %7B%0A        return next;%0A    %7D%0A%0A    // hasNext() and next() should behave the same as in the Iterator interface.%0A    // Override them if needed.%0A    @Override%0A    public Integer next() %7B%0A        int res = next;%0A        next = iter.hasNext() ? iter.next() : null;%0A        return res;%0A    %7D%0A%0A    @Override%0A    public boolean hasNext() %7B%0A        return next != null;%0A    %7D%0A%0A%7D%0A

add 284 Peeking Iterator