My Java solution


  • 9
    Q
    class PeekingIterator implements Iterator<Integer> {
        Integer n = null;
        private Iterator<Integer> iterator = null;
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    this.iterator = iterator;
    	}
    
        public Integer peek() {
            if (n == null && iterator.hasNext()){
                n = iterator.next();
            }
            return n;
    	}
    	public Integer next() {
    	    if (n!=null){
    	        int temp = n;
    	        n = null;
    	        return temp;
    	    }
    	    return iterator.next();
    	}
    	public boolean hasNext() {
    	    if (n!=null){
    	        return true;
    	    }
    	    return iterator.hasNext();
    	}
    }

  • 0

    I think it's unsafe to implement hasNext based on the test of n is null, unless it's guranteed that there is no null-element in the collection.
    While system test cases doens't include such a case of null element.


  • 0
    Z

    I have the same confusion...


  • 0
    H

    Can anyone explain how iterator.next() and iterator.hasNext() work if n == null?


Log in to reply
 

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