Easy solution using queue


  • 0
    D
    class PeekingIterator implements Iterator<Integer> {
    private Queue<Integer> q;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        // initialize any member here.
        q=new LinkedList<Integer>();
       while(iterator.hasNext()){
           q.offer(iterator.next());
           
       }
     
    }
    
    // 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.
    @Override
    public Integer next() {
       if(!q.isEmpty()) return q.poll();
       else return null;
    }
    
    @Override
    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.