Keep the iterator 1 step ahead, c++ code


  • 1
    T

    By keeping the iterator one step advanced, we get a simpler peek and hasnext operation. Could someone comment on the pro and con of doing it this way vs the guava way? Thanks.

    class PeekingIterator : public Iterator {
    public:
        int peekedElement;
        bool hasNextElement;
       
    
    	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    	    hasNextElement = Iterator::hasNext();
    	    peekedElement  = Iterator::next();
    	}
    
    	int peek() {
            return peekedElement;
    	}
    
    	int next() {
    	    int tmp = peekedElement;
    	    hasNextElement = Iterator::hasNext();
    	    if (hasNextElement)
    	        peekedElement  = Iterator::next();
    	    return tmp;
    	}
    
    	bool hasNext() const {
    	    return hasNextElement;
    	}
    };

Log in to reply
 

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