Accepted Java Solution Peeking Iterator


  • 3
    V

    class PeekingIterator implements Iterator<Integer> {

    private Iterator<Integer> iter;
    private Integer v;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        this.iter = iterator;
        v = null;
        
    }
    
    
    public Integer peek() {
        if(v == null){
            v = iter.next();
        }
        return v;
    }
    
    
    @Override
    public Integer next() {
        Integer tmp = null;
        if(v == null){
            v = iter.next();
            tmp = v;
            v = null;
            return tmp;
        }
        tmp = v;
        v = null;
        return tmp;
        
    }
    
    @Override
    public boolean hasNext() {
       if(v != null){
           return true;
       } 
       return iter.hasNext();
    }
    

    }


Log in to reply
 

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