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

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

LeetCode上的原题,请参见我之前的博客Flatten Nested List Iterator。但是不太明白的是,那篇博客中的解法三可以通过LeetCode的OJ,在LintCode上跑就有错误,不知道啥原因。

解法一:

class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - ; i >= ; --i) {
s.push(nestedList[i]);
}
} int next() {
NestedInteger t = s.top(); s.pop();
return t.getInteger();
} bool hasNext() {
while (!s.empty()) {
NestedInteger t = s.top();
if (t.isInteger()) return true;
s.pop();
for (int i = t.getList().size() - ; i >= ; --i) {
s.push(t.getList()[i]);
}
}
return false;
} private:
stack<NestedInteger> s;
};

解法二:

class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (auto a : nestedList) {
d.push_back(a);
}
} int next() {
NestedInteger t = d.front(); d.pop_front();
return t.getInteger();
} bool hasNext() {
while (!d.empty()) {
NestedInteger t = d.front();
if (t.isInteger()) return true;
d.pop_front();
for (int i = ; i < t.getList().size(); ++i) {
d.insert(d.begin() + i, t.getList()[i]);
}
}
return false;
} private:
deque<NestedInteger> d;
};

最新文章

  1. Mybatis框架 的快速入门
  2. tp框架的增删改查
  3. UTC时间和本地时间的区别
  4. 【JUC】JDK1.8源码分析之ReentrantLock(三)
  5. Java避免创建不必要的对象
  6. Blend 2015 教程 (四)控件模板
  7. shell 中 &amp;&amp;和||的方法
  8. http://www.cnblogs.com/0201zcr/p/4987561.html
  9. WEB前端的原理及组成
  10. canvas API ,通俗的canvas基础知识(二)
  11. 夺命雷公狗---DEDECMS----33dedecms自定义搜索以及分页功能完成
  12. Dockpanel的控件加载问题
  13. (转)Redis 集群方案
  14. Php开源项目大全
  15. [项目记录] 用c语言完成的一个学生成绩管理系统
  16. XenServer多网卡绑定
  17. Kb和KB的区别
  18. 安卓开发----TextView控件属性列表(转)
  19. List集合实现简易学生管理
  20. 工作中用到和应该知道的eclipse快捷键

热门文章

  1. 咱就入个门之NHibernate映射文件配置(一)
  2. [Liferay6.2]核心配置文件portal.properties
  3. 64位ubuntu下重新编译hadoop2.2流水账
  4. AOP动态代理解析2-代码织入入口
  5. Swift3.0语言教程分割字符串与截取字符串
  6. 【CLR in c#】属性
  7. 我的c++学习(1)hello world!
  8. POJ2976 Dropping tests(01分数规划)
  9. apache activemq 学习笔记
  10. [转]crontab命令指南