Simple and clean Java - use single cache


  • 0
    J
    class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> it;
    private Integer cache;
    public PeekingIterator(Iterator<Integer> iterator) {
    	it = iterator;
    	cache = null; //empty cache
    }
    public Integer peek() {
        if (cache == null)
        	cache = it.next();
        return cache;
    }
    @Override
    public Integer next() {
    	Integer next;
    	if (cache != null) {
    		next = cache;
    	} else {
    		next = it.next();
    	}
    	cache = null;  //clear cache
    	return next;
    }
    @Override
    public boolean hasNext() {
        if (cache != null || it.hasNext())
        	return true;
        else
        	return false;
    } }

Log in to reply
 

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