C++ well structured class (extracted list2Stack and uncompressFirstInteger)


  • 0

    This is the popular stack solution that many have posted here. I think we should extract those two private methods to make the class more readable.

    class NestedIterator {
        
    private:
        stack<NestedInteger> _s;
        
        void list2Stack(vector<NestedInteger> &list) {
            for (int i = list.size()-1; i >= 0; --i) _s.push(list[i]);
        }
        
        void uncompressFirstInteger() {
            while (!_s.empty()) {
                auto t = _s.top();
                if (t.isInteger()) return;
                else _s.pop(), list2Stack(t.getList());
            }
        }
        
    public:
        NestedIterator(vector<NestedInteger> &list) {
            list2Stack(list);
            uncompressFirstInteger();
        }
    
        int next() {
            int res = _s.empty()? INT_MIN : _s.top().getInteger();
            _s.pop(), uncompressFirstInteger();
            return res;
        }
    
        bool hasNext() {
            return !_s.empty();
        }
    };
    
    

Log in to reply
 

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