C++ 4ms solution


  • 0
    A
    class PeekingIterator : public Iterator {
    public:
    	PeekingIterator(const vector<int>& nums) : Iterator(nums) {}
    
    	int peek() {
            if (peeked_) {
                return next_val_;
            }
            next_val_ = Iterator::next();
            peeked_ = true;
            return next_val_;
    	}
    
    	int next() {
    	    if (peeked_) {
    	        peeked_ = false;
    	        return next_val_;
    	    }
    	    return Iterator::next();
    	}
    
    	bool hasNext() const {
    	    if (peeked_) {
    	        return true;
    	    }
    	    return Iterator::hasNext();
    	}
    	
    private:
        bool peeked_ = false;
        int next_val_ = 0;
    };

Log in to reply
 

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