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. Convert 输入字符串的格式不正确

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...

  2. django-模板变量forloop

    在django的模板中,有forloop这一模板变量,颇似php Smarty中的foreach.customers, Smarty foreach如下: {foreach name=customer ...

  3. 使用mybatis框架实现带条件查询-单条件

    之前我们写的查询sql都是没有带条件的,现在来实现一个新的需求,根据输入的字符串,模糊查询用户表中的信息 UserMapper.xml UserMapper.java 与jdbc的比较: 编写测试方法 ...

  4. git和bootstrap

    在linux系统中某种类型的服务有没有启动:ps -ef|grep 对应的服务名称 然后修改gitlab中的两个配置文件的信息 一般情况下是先创建组,然后在创建项目 常见的协议有http协议   ss ...

  5. tensorflow API _ 4 (优化器配置)

    """Configures the optimizer used for training. Args: learning_rate: A scalar or `Tens ...

  6. 洛谷 SP338 ROADS - Roads 题解

    思路 dfs(只不过要用邻接表存)邻接表是由表头结点和表结点两部分组成,其中表头结点存储图的各顶点,表结点用单向链表存储表头结点所对应顶点的相邻顶点(也就是表示了图的边).在有向图里表示表头结点指向其 ...

  7. 好的想法只是OKR的开始--创业者谨记

    每一个出版过作品的作家都有这样的体验:有人找到你,说他有一个极妙的想法,并迫不及待的想和你一起实现这个想法:结局也总是差不多,它们艰难的完成了灵感部分,而你只需要简单的把它写成小说,收益则需要五五分成 ...

  8. Web 项目的文件/文件夹上传下载

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...

  9. learning java FileReader

    import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import ...

  10. WinDbg命令窗口的使用

    调试器命令窗口是windbg中的主要调试信息窗口.可以在此窗口中输入调试程序命令并查看命令输出.Windbg的命令窗口是我们进行调试时,主要打交道的窗口.界面如下 对于windbg,“调试器命令窗口” ...