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

将1个含有整数元素的嵌套链表压平,就是把所以元素按嵌套关系变成1个list。按题目要求要有next和hasNext两个函数。

Java:

public class NestedIterator implements Iterator<Integer> {
Stack<NestedInteger> stack; public NestedIterator(List<NestedInteger> nestedList) {
stack = new Stack<>();
pushData(nestedList);
} @Override
public Integer next() {
return stack.pop().getInteger();
} @Override
public boolean hasNext() {
while(!stack.isEmpty()) {
if (stack.peek().isInteger()) {
return true;
}
pushData(stack.pop().getList());
}
return false;
} private void pushData(List<NestedInteger> nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
} /**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/  

Python: stack

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """ class NestedIterator(object): def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.stack = []
self.list = nestedList def next(self):
"""
:rtype: int
"""
return self.stack.pop() def hasNext(self):
"""
:rtype: bool
"""
while self.list or self.stack:
if not self.stack:
self.stack.append(self.list.pop(0))
while self.stack and not self.stack[-1].isInteger():
top = self.stack.pop().getList()
for e in top[::-1]:
self.stack.append(e)
if self.stack and self.stack[-1].isInteger():
return True
return False # Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())  

Python: queue

class NestedIterator(object):

    def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.queue = collections.deque()
def getAll(nests):
for nest in nests:
if nest.isInteger():
self.queue.append(nest.getInteger())
else:
getAll(nest.getList())
getAll(nestedList) def next(self):
"""
:rtype: int
"""
return self.queue.popleft() def hasNext(self):
"""
:rtype: bool
"""
return len(self.queue) # Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

C++: stack

class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; --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() - 1; i >= 0; --i) {
s.push(t.getList()[i]);
}
}
return false;
} private:
stack<NestedInteger> s;
};

C++:deque

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 = 0; i < t.getList().size(); ++i) {
d.insert(d.begin() + i, t.getList()[i]);
}
}
return false;
} private:
deque<NestedInteger> d;
};

C++: Recursion

class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
make_queue(nestedList);
} int next() {
int t = q.front(); q.pop();
return t;
} bool hasNext() {
return !q.empty();
} private:
queue<int> q;
void make_queue(vector<NestedInteger> &nestedList) {
for (auto a : nestedList) {
if (a.isInteger()) q.push(a.getInteger());
else make_queue(a.getList());
}
}
};

All LeetCode Questions List 题目汇总

[LeetCode] 341. Flatten Nested List Iterator 压平嵌套链表迭代器的更多相关文章

  1. [LeetCode] Flatten Nested List Iterator 压平嵌套链表迭代器

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  2. [LintCode] Flatten Nested List Iterator 压平嵌套链表迭代器

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

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

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  4. LeetCode 341. Flatten Nested List Iterator

    https://leetcode.com/problems/flatten-nested-list-iterator/

  5. 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...

  6. [Swift]LeetCode341. 压平嵌套链表迭代器 | Flatten Nested List Iterator

    Given a nested list of integers, implement an iterator to flatten it. Each element is either an inte ...

  7. 【leetcode】341. Flatten Nested List Iterator

    题目如下: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...

  8. 341. Flatten Nested List Iterator展开多层数组

    [抄题]: Given a nested list of integers, implement an iterator to flatten it. Each element is either a ...

  9. 341. Flatten Nested List Iterator

    List里可以有int或者List,然后里面的List里面可以再有List. 用Stack来做比较直观 Iterator无非是next()或者hasNext()这2个方程 一开始我想的是hasNext ...

随机推荐

  1. Relief 过滤式特征选择

    给定训练集{(x1,y1),(x2,y2).....(xm,ym)} ,对每个示例xi,Relief在xi的同类样本中寻找其最近邻xi,nh(猜中近邻),再从xi的异类样本中寻找其最近邻xi,nm(猜 ...

  2. c++实现按行读取文本文件

    包含头文件fstream既可以读又可以写(我的理解是头文件fstream中包含ifstream和ofstream),可以同时创建ifstream对象和ofstream对象,分别实现读写:也可以直接创建 ...

  3. 开发环境搭建之springboot+tk.mybatis整合使用逆向工程

    一,引入xml文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorCo ...

  4. janusgraph-图数据库的学习(2)

    janusgraph的简单使用 当安装好以后简单的使用janusgraph 1.进入janusgraph的shell命令界面 [root@had214 janusgraph-0.3.1-hadoop2 ...

  5. K-Nearest Neighbors Algorithm

    K近邻算法. KNN算法非常简单,非常有效.KNN算法适合样本较少典型性较好的样本集. KNN的模型表示是整个训练数据集.也可以说是:KNN的特点是完全跟着数据走,没有数学模型可言. 对一个新的数据点 ...

  6. solidworks 学习 (三)

    汽车轮毂三维建模

  7. js傻瓜式制作电子时钟

    js傻瓜式制作电子时间 使用到的知识点 setInterval函数 构建函数new Date if判断 demo: //css样式请自行设置 <span id="timer" ...

  8. vlang module 使用

    vlang 支持module,概念以及使用类似rust 以及golang 的gopath(从当前的文档以及使用来说),但是还不完整 以及是够用,但是有问题 v module 试用 项目结构   ├── ...

  9. box-sizing 盒子模型

    一.概念 ①外加模式: box-sizing: content-box 这是由 CSS2.1 规定的宽度高度行为.宽度和高度分别应用到元素的内容,在宽度和高度之外绘制元素的内边距,即宽和高不包括内边距 ...

  10. 1、zookeeper入门

    一.什么是Zookeeper Zookeeper是Google的Chubby一个开源的实现,是一个开源的,为分布式提供协调服务的Apache项目; 它包含一个简单的原语集,分布式应用程序可以基于它实现 ...