Concise and Clean Java Solution


  • 2
    J

    Simple helper function make things easier

    class PeekingIterator implements Iterator<Integer> {
    	private Iterator<Integer> iterator;
    	private Integer curr;
    	private boolean next;
    
    	public PeekingIterator(Iterator<Integer> iterator) {
    		this.iterator = iterator;
    		prepareNext();
    	}
    
    	private void prepareNext() {
    	    next = iterator.hasNext();
    	    curr = next ? iterator.next() : null;
    	}
    
    	public Integer peek() {
    		return curr;
    	}
    
    	@Override
    	public Integer next() {
    		Integer val = curr;
    		prepareNext();
    		return val;
    	}
    
    	@Override
    	public boolean hasNext() {
    		return next;
    	}
    }

Log in to reply
 

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