Another C++ solution with one line in peek() and hasNext(), AC


  • 27
    W
    class PeekingIterator : public Iterator {
    private:
        int m_next;
        bool m_hasnext;
    public:
    	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    	    m_hasnext = Iterator::hasNext();
    	    if (m_hasnext) m_next = Iterator::next();
    	}
    
    	int peek() {
            return m_next;
    	}
    
    	int next() {
    	    int t = m_next;
    	    m_hasnext = Iterator::hasNext();
    	    if (m_hasnext) m_next = Iterator::next();
    	    return t;
    	}
    
    	bool hasNext() const {
    	    return m_hasnext;
    	}
    };

  • 0
    Y

    if (m_hasnext) m_next = Iterator::next(); For this expression. will the use of Iterator::next() lead to a problem that when we firstly use PeekingIterator::next(), it may return the second number not the first number?


  • 0
    K

    Unless you use the same vector to init two iterators, which is not in the requirement of the question.


Log in to reply
 

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