码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Flatten Nested List Iterator"

时间:2016-04-06 07:05:33      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Besides the common stack-based solutions, here is another recursive NestedIterator solution :)

class NestedIterator 
{
    int currInx;
    const vector<NestedInteger> &rData;    
    NestedIterator *sub;

    void move()
    {
        if (currInx < 0 || rData[currInx].isInteger() || !sub->hasNext())
        {
            if ((++currInx) < rData.size())
            {    
                releaseSub();
                if (!rData[currInx].isInteger())
                {
                    // get next non-empty list
                    while (currInx < rData.size() &&
                            ( sub = new NestedIterator(const_cast<vector<NestedInteger>&>(rData[currInx].getList())),
                              (!rData[currInx].isInteger() && sub && !sub->hasNext())) )
                    {
                        currInx++;
                        releaseSub();
                    }
                }
            }
        }
        else
        {
            sub->move();
        }
    }
    //
    NestedIterator() 
        :rData(vector<NestedInteger>()), currInx(-1), sub(nullptr)
    { }

    void releaseSub()
    {
        delete sub;    sub = nullptr;
    }
    
public:
    ~NestedIterator()
    {
        releaseSub();
    }
    
    NestedIterator(vector<NestedInteger> &nestedList) 
        :rData(nestedList), currInx(-1), sub(nullptr)
    {
        move();
    }

    int next() 
    {
        int val = 0;
        if (rData[currInx].isInteger())
        {
            val = rData[currInx].getInteger();
            move();
        }
        else
        {
            val = sub->next();
            if (!sub->hasNext()) move();
        }        
        return val;
    }

    bool hasNext() 
    {
        return currInx < rData.size() && (rData[currInx].isInteger() || sub->hasNext());
    }
};

 

LeetCode "Flatten Nested List Iterator"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5357664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!