56 ms stack-based c++ solution


  • 0
    S
    class NestedIterator {
    private:
        stack<NestedInteger> st;
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for (auto iter = nestedList.rbegin(); iter != nestedList.rend(); iter++) {
                st.push(*iter);
            }
        }
    
        int next() {
            NestedInteger cur = st.top();
            if (cur.isInteger()) {
                st.pop();
                return cur.getInteger();
            }
            else {
                st.pop();
                vector<NestedInteger> list = cur.getList();
                for (auto iter = list.rbegin(); iter != list.rend(); iter++) {
                    st.push(*iter);
                }
                return next();
            }
        }
    
        bool hasNext() {
            if (st.empty()) return false;
            
            NestedInteger cur = st.top();
            if (cur.isInteger()) return true;
            else {
                st.pop();
                vector<NestedInteger> list = cur.getList();
                for (auto iter = list.rbegin(); iter != list.rend(); iter++) {
                    st.push(*iter);
                }
                return hasNext();
            }
        }
    };

Log in to reply
 

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