Easy solution using queue

  • 0
    class PeekingIterator implements Iterator<Integer> {
    private Queue<Integer> q;
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        q=new LinkedList<Integer>();
    // Returns the next element in the iteration without advancing the iterator.
    public Integer peek() {
        return q.peek();
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    public Integer next() {
       if(!q.isEmpty()) return q.poll();
       else return null;
    public boolean hasNext() {
        return !q.isEmpty();


Log in to reply

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