Simple Solution in Java using Queue


  • 0
    S

    // Java Iterator interface reference:
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {
    static Queue<Integer> queue = new LinkedList<Integer>();

    public PeekingIterator(Iterator<Integer> iterator) {
        while (iterator.hasNext()) {
            queue.add(iterator.next());
        }
        
    }
    
    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return queue.peek();
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public Integer next() {
        return queue.poll();
    }
    
    @Override
    public boolean hasNext() {
        return !queue.isEmpty();    
    }
    

    }


  • 1
    D

    Thanks for your solution.

    I have a question: does using a queue performs better than an iterator as instance variable?


  • 0
    S

    No. It doesn't perform better.


  • -2
    B

    I think in the problem hopes you do not manipulate the integers. :)


  • 0
    A

    The difference would be the amount of preprocessing done by the constructor to put everything into a queue. Imagine having to scan a huge document immediately, You would have to wait till the entire document is processed before you can began "iterating" it with a peek functionality. If the user doesn't even need the entire document it is a bunch of wasted cycles preprocessing the data.

    It may be an elegant solution and its takes advantage of the properties of a queue, but it may not be preferable due to preprocessing. All in all it, it is a solution.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.