341. Flatten Nested List Iterator

48 篇文章 0 订阅
43 篇文章 0 订阅

原题:

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].

分析

题目要求,给定一个嵌套列表,实现按照顺序访问他的迭代器
该嵌套列表的结构式,每个元素要么是整数要么是列表,然后他们的元素也是整数或者列表。

从其中可以看出,这个结构具有递归特性。所以我们应该意识到使用递归来解决该问题。

首先我们定义一个全局的vector NestVector来存放我们遍历的结果,然后定义一个全局的游标,index来标记访问到那个元素。
然后在构造函数中,通过递归方式实现对嵌套列表的访问,并将结果存入NestVector中。

对于hasNext()函数,只需要判断游标是否到达NestVector末尾即可

对于next()函数,我们只需要范围NestVector中,当前index位置处的值即可。然后对index加一即可。

代码

class NestedIterator {
public:
    vector<int> NestVector;
    int index;

    NestedIterator(vector<NestedInteger> &nestedList) {
        VisitNestedList(nestedList);
        index = 0;
    }

    //递归遍历
    void VisitNestedList(vector<NestedInteger> &nestedList){
         for(int i = 0; i < nestedList.size(); i++){
            if(nestedList[i].isInteger()){
                       NestVector.push_back(nestedList[i].getInteger());
            }else{
                VisitNestedList(nestedList[i].getList());
            }
        }
    }

    int next() {
        return NestVector[index++];
    }

    bool hasNext() {
       if(index < NestVector.size()){
           return true;
       }else{
           return false;
       }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值