C++ simple solution


  • 0
    // Below is the interface for Iterator, which is already defined for you.
    // **DO NOT** modify the interface for Iterator.
    class Iterator {
        struct Data;
    	Data* data;
    public:
    	Iterator(const vector<int>& nums);
    	Iterator(const Iterator& iter);
    	virtual ~Iterator();
    	// Returns the next element in the iteration.
    	int next();
    	// Returns true if the iteration has more elements.
    	bool hasNext() const;
    };
    
    
    class PeekingIterator : public Iterator {
    public:
        int num;
        bool flag;
    	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    	    flag = false;
    	}
    
    	int peek() {
    	    if (!flag) {
                    num = Iterator::next();
                    flag = true;
                    return num;
    	    }
            return num;
    	}
    
    	int next() {
    	    if (!flag) {
    	        return Iterator::next();
    	    }
    	    flag = false;
    	    return num;
    	}
    
    	bool hasNext() const {
    	    return flag || Iterator::hasNext();
    	}
    };
    

Log in to reply
 

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