Share my cpp and python solution with recursion


  • 0
    Z

    cpp solution

    class NestedIterator {
    public:
    
    vector<int> my_list;
    int index = 0;
    NestedIterator(vector<NestedInteger> &nestedList) {
        for(int i=0;i<nestedList.size();i++){
            if(nestedList[i].isInteger())
                my_list.push_back(nestedList[i].getInteger());
            else
                read_list(nestedList[i].getList());
        }
    }
    
    void read_list(vector<NestedInteger> &nestedList){
        for(int i=0;i<nestedList.size();i++){
            if(nestedList[i].isInteger())
                my_list.push_back(nestedList[i].getInteger());
            else
                read_list(nestedList[i].getList());
        }
    }
    
    int next() {
        int re = my_list[index];
        index++;
        return re;
    }
    
    bool hasNext() {
        if(index == my_list.size())
            return 0;
        return 1;
    }
    };
    

    python solution

    class NestedIterator(object):
    
    def __init__(self, nestedList):
        self.my_list = []
        self.index = 0
        for i in nestedList:
            if i.isInteger() == True:
                self.my_list.append(i.getInteger())
            else:
                self.read_list(i.getList())
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
    def read_list(self,l):
        for i in l:
            if i.isInteger() == True:
                self.my_list.append(i.getInteger())
            else:
                self.read_list(i.getList())
    
    
    def next(self):
        """
        :rtype: int
        """
        re = self.my_list[self.index]
        self.index += 1
        return re
        
    
    def hasNext(self):
        """
        :rtype: bool
        """
        if self.index == len(self.my_list):
            return False
        return True

Log in to reply
 

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