Real iterator c++ solution,44ms


  • 2
    Z
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for(int i=nestedList.size()-1;i>=0;i--){
            int* t=new int(0);
            st.push({&(nestedList[i]),t});
            }
        }
        int next() {
            return nxt;
        }
        bool hasNext() {
            if(st.empty())return false;
            NestedInteger* tmp=st.top().first;
            int* num=st.top().second;
             if(tmp->isInteger()){
                 nxt=tmp->getInteger();
                 st.pop();return true;
             }
             else{
                 if(tmp->getList().size()==*num){
                     st.pop();
                     
                 }
                 else{
                     int *t=new int(0);
                     st.push({&(tmp->getList()[*num]),t});
                     (*num)++;
                 }
                 return hasNext();
             }
        }
    private:
        stack<pair<NestedInteger*,int*>> st;
        int nxt;
    };

Log in to reply
 

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