No stack just one int one bool


  • 0
    S
    class PeekingIterator : public Iterator {
    public:
    	PeekingIterator(const vector<int>& nums) : Iterator::Iterator(nums) {
    	    // Initialize any member here.
    	    // **DO NOT** save a copy of nums and manipulate it directly.
    	    // You should only use the Iterator interface methods.
    	   val = 0;
    	   ahead = false;
    	}
    
    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        if (!ahead){
            val = Iterator::next();
            ahead = true;
        }
        return val;
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        if (!ahead) return Iterator::next();
        else {
            ahead = false;
            return val;
        }
    }
    
    bool hasNext() const {
        if (ahead) return true;
        return Iterator::hasNext();
    }
    private:
        int val;
        bool ahead;
    };

Log in to reply
 

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