C++ code of this problem


  • 2
    L
    class PeekingIterator : public Iterator {
        
        int peekele;
        bool peeked;
        
    public:
    	PeekingIterator(const vector<int>& num) : Iterator(num) {
    	    // Initialize any member here.
    	    peeked = false;
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	int peek() {
            if(!peeked) {
                peekele = Iterator::next();
                peeked = true;
            }
            return peekele;
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	int next() {
    	    if(!peeked) return Iterator::next();
            peeked = false;
            return peekele;
    	}
    
    	bool hasNext() const {
    	    if(peeked) return true;
    	    if(Iterator::hasNext()) return true;
    	    return false;
    	}
    };

  • 0
    H

    Can I ask a question in bool hasNext() const {
    if(peeked) return true;
    if(Iterator::hasNext()) return true;
    return false;
    }

    It seems that the function calls itself in the second line, like

    if(Iterator::hasNext()) return true;

    I do not understand this part .

    Thanks.


  • 0

    It calls the super class Iterator's hasNext() method, so it's not calling itself.


  • 0
    H

    thanks for the quick response. Now I understand, it calls the hasnext function from the class iterator, not from peekIterator.


Log in to reply
 

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