10-line C++ and 14-line Java Implementation


  • 12
    class PeekingIterator : public Iterator {
        bool hasPeeked;
        int peekedElem;
    public:
    	PeekingIterator(const vector<int>& num) : Iterator(num) {
            hasPeeked = false;
    	}
    
    	int peek() {
            peekedElem = hasPeeked?peekedElem:Iterator::next();
            hasPeeked = true;
            return peekedElem;
    	}
    
    	int next() {
    	    int nextElem = hasPeeked?peekedElem:Iterator::next();
    	    hasPeeked = false;
    	    return nextElem;
    	}
    
    	bool hasNext() const {
    	    return hasPeeked||Iterator::hasNext();
    	}
    };  
    

    Java implementation, inspired by Google's guava library source code.

    class PeekingIterator implements Iterator<Integer> {
        private final Iterator<Integer> iterator;
        private boolean hasPeeked;
        private Integer peekedElement;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    if(iterator==null)
    	        throw new NullPointerException();
    	    else
    	        this.iterator = iterator;
    	}
    
    	public Integer peek() {
            peekedElement = hasPeeked?peekedElement:iterator.next();
            hasPeeked = true;
            return peekedElement;
    	}
    
    	@Override
    	public Integer next() {
    	    int nextElem = hasPeeked?peekedElement:iterator.next();
            hasPeeked = false;
            return nextElem;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return hasPeeked || iterator.hasNext();
    	}
    }

  • 0

    Guava does something pointless like iterator==null?null:iterator?


  • 0

    Oh sorry I mistakenly interpreted the checkNotNull() method. Now I stick to the original semantic. Thank you for pointing out!


Log in to reply
 

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