Java no memory solution


  • 0
    S
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {
        
        Integer peek;
        Iterator<Integer> iter;
    
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    this.iter = iterator;
    	    if (iter.hasNext())
    	        this.peek = iter.next();
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
            return peek;
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next() {
    	    Integer temp = this.peek;
    	    if (iter.hasNext())
    	        this.peek = iter.next();
            else
                this.peek = null;
            return temp;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return iter.hasNext() || peek != null;
    	}
    }

Log in to reply
 

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