A simple C++ solution


  • 0
    Y
    
    class Iterator {
        struct Data;
    	Data* data;
    public:
    	Iterator(const vector<int>& nums);
    	Iterator(const Iterator& iter);
    	virtual ~Iterator();
    	int next();
    	bool hasNext() const;
    };
    
    
    class PeekingIterator : public Iterator {
    public:
    	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
            move_forward();
    	}
    
    	int peek() {
            return m_next_val;
    	}
    
    	int next() {
    	    int reval(m_next_val);
    	    move_forward();
            return reval;
    	}
    
    	bool hasNext() const {
    	    return m_has_next;
    	}
    private:
        void move_forward () {
            if ( Iterator::hasNext() ) {
               m_next_val = Iterator::next();
               m_has_next = true;
            } else {
                m_has_next = false;
                m_next_val = INT_MIN;
            }
        }
        // m_next_val always pointed to the next value
        int m_next_val; 
        bool m_has_next;
    };
    

Log in to reply
 

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