Simple C++ solution using queue


  • 0
    B
    class NestedIterator {
        queue<int> q;
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            NestedIteratorHelper(nestedList);
        }
        void NestedIteratorHelper(vector<NestedInteger> &nestedList) {
            int size = nestedList.size();
            for (int i = 0; i < size; i++) {
                NestedInteger tmp = nestedList[i];
                if (tmp.isInteger()) {
                    q.push(tmp.getInteger());
                }
                else {
                    NestedIterator(tmp.getList());
                }
            }
        }
        
        int next() {
            if (hasNext()) {
                int a = q.front();
                q.pop();
                return a;
            }
        }
    
        bool hasNext() {
            return (!q.empty());
        }
    };

Log in to reply
 

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