Share my C++ solutions,easy to understand


  • 0
    V
    class NestedIterator {
    private:
        stack<NestedInteger> s;
        
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            int len = nestedList.size();
            int i = 0;
            
            for (i = len - 1; i >= 0; i--)
            {
                s.push(nestedList[i]);
            }
        }
    
        int next() {
            NestedInteger temp = s.top();
            s.pop();
            
            return temp.getInteger();
        }
    
        bool hasNext() {
            while (!s.empty())
            {
                NestedInteger temp = s.top();
                if (temp.isInteger())
                    return true;
                else
                {
                    s.pop();
                    vector<NestedInteger> list = temp.getList();
                    int len = list.size();
                    int i = 0;
                    
                    for (i = len - 1; i >= 0; i--)
                    {
                        s.push(list[i]);
                    }
                }
            }
            
            return false;
        }
    };

  • 0
    V

    The following is faster

    class NestedIterator {
    private:
        stack<int> s;
        
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            flatten(nestedList);
        }
    
        int next() {
            int ret = s.top();
            s.pop();
            
            return ret;
        }
    
        bool hasNext() {
            return !s.empty();
        }
        
        void flatten(vector<NestedInteger> &nestedList)
        {
            int i = 0;
            int len = nestedList.size();
            
            for (i = len - 1; i >= 0; i--)
            {
                if (nestedList[i].isInteger())
                    s.push(nestedList[i].getInteger());
                else
                    flatten(nestedList[i].getList());
            }
        }
    };

  • 0
    P

    Note this one uses O(n) space.


Log in to reply
 

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