C++ solution using a stack


  • 2
    S
      class PeekingIterator : public Iterator {
        public:
        	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
        	    it = this;
        	}
        
            // Returns the next element in the iteration without advancing the iterator.
        	int peek() {
                if (pk.empty()) {
                    pk.push(next());
                }
                
                return pk.top();
        	}
        
        	// hasNext() and next() should behave the same as in the Iterator interface.
        	// Override them if needed.
        	int next() {
        	    int val;
        	    if (!pk.empty()) {
        	        val = pk.top();
        	        pk.pop();
        	    } else {
        	        val = it->next();
        	    }
        	    
        	    return val;
        	}
        
        	bool hasNext() const {
        	    return !pk.empty() || it->hasNext();
        	}
        	
        private:
            Iterator *it;
            stack<int> pk;
        };

  • 1
    A

    You don't need to use a stack. A int variable is enough, because your stack only has at most one element.


  • 0
    S

    But you also need a flag to detect the variable is set or not.


  • 0
    A

    That's true. I use INT_MAX to mark as null because I make an assumption that input should never be INT_MAX.


  • 0
    G

    When the input has a value of INT_MAX or INT_MIN or other value that you used as mark, the method is no longer correct.


Log in to reply
 

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