leetcode 341. Flatten Nested List Iterator

Posted godjob

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 341. Flatten Nested List Iterator相关的知识,希望对你有一定的参考价值。

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

Example 2:
Given the list [1,[4,[6]]],

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].

Subscribe to see which companies asked this question

 

很显然这个是一个递归问题,但是题目要求实现一个迭代器,这里我想到两个方法:
1. 直接在构造函数中使用递归构造好整个序列,然后逐个返回
2.栈保存历史记录,栈顶保存当前打印的列表以及打印到列表哪个位置,刚开始实现很顺利,但是后面提交发现测试用例有空列表的情况,如输入为[[],[[]]],这个
就麻烦了,该进后的方式就是保存一个缓存节点
下面是自己实现的方法:
 
#include <stack>
#include <vector>
#include <assert.h>
struct NestedContext {
    const vector<NestedInteger>* vec;
    size_t pos;
};

class NestedIterator {
public:
    NestedIterator(vector<NestedInteger> &nestedList)
    {
        has_next = true;
        if (nestedList.empty()) {
            return;
        }
        NestedContext ctx = {&nestedList, 0};
        s.push(ctx);
    }
    int next() {
        return cache_val;
    }

    bool _next(int& val) {
        while (!s.empty()) {
            NestedContext& ctx = s.top();
            if (ctx.vec->at(ctx.pos).isInteger()) {
                int rv = ctx.vec->at(ctx.pos++).getInteger();
                if (ctx.pos >= ctx.vec->size()) {
                    s.pop();
                }
                val = rv;
                return true;
            }
            else {
                const vector<NestedInteger>& nestedList = ctx.vec->at(ctx.pos++).getList();
                if (ctx.pos >= ctx.vec->size()) {
                    s.pop();
                }
                if (!nestedList.empty()) {
                    NestedContext new_ctx = {&nestedList, 0};
                    s.push(new_ctx);
                }
            }
        }
        return false;
    }

    bool hasNext() {
        has_next = _next(cache_val);
        return !s.empty() || has_next;
    }
    stack<NestedContext> s;
    bool has_next;
    int cache_val;
};

 

以上是关于leetcode 341. Flatten Nested List Iterator的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 341. Flatten Nested List Iterator

leetcode341. Flatten Nested List Iterator

[leetcode]341. Flatten Nested List Iterator 展开嵌套列表的迭代器

341. Flatten Nested List Iterator

341. Flatten Nested List Iterator

341. Flatten Nested List Iterator