C++ solution using a stack

  • 2
      class PeekingIterator : public Iterator {
        	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()) {
                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();
        	    } else {
        	        val = it->next();
        	    return val;
        	bool hasNext() const {
        	    return !pk.empty() || it->hasNext();
            Iterator *it;
            stack<int> pk;

  • 1

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

  • 0

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

  • 0

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

  • 0

    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.