Simplest Java Solution


  • 0
    J
    class PeekingIterator implements Iterator<Integer> {
    
    private Iterator<Integer> iterator;    
    private Integer num;
    
    public PeekingIterator(Iterator<Integer> iterator) {
        this.iterator = iterator;
    }
    
    public Integer peek() {
        if (num != null) return num;
        return num = iterator.next();
    }
    
    @Override
    public Integer next() {
        if (num != null) {
            Integer result = num;
            num = null;
            return result;
        }
        return iterator.next();
    }
    
    @Override
    public boolean hasNext() {
        return num != null || iterator.hasNext();
    }
    }

Log in to reply
 

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