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:

  1. public class NestedIterator implements Iterator<Integer> {
  2. Stack<NestedInteger> stack;
  3.  
  4. public NestedIterator(List<NestedInteger> nestedList) {
  5. stack = new Stack<>();
  6. pushData(nestedList);
  7. }
  8.  
  9. @Override
  10. public Integer next() {
  11. return stack.pop().getInteger();
  12. }
  13.  
  14. @Override
  15. public boolean hasNext() {
  16. while(!stack.isEmpty()) {
  17. if (stack.peek().isInteger()) {
  18. return true;
  19. }
  20. pushData(stack.pop().getList());
  21. }
  22. return false;
  23. }
  24.  
  25. private void pushData(List<NestedInteger> nestedList) {
  26. for (int i = nestedList.size() - 1; i >= 0; i--) {
  27. stack.push(nestedList.get(i));
  28. }
  29. }
  30. }
  31.  
  32. /**
  33. * Your NestedIterator object will be instantiated and called as such:
  34. * NestedIterator i = new NestedIterator(nestedList);
  35. * while (i.hasNext()) v[f()] = i.next();
  36. */  

Python: stack

  1. # """
  2. # This is the interface that allows for creating nested lists.
  3. # You should not implement it, or speculate about its implementation
  4. # """
  5. #class NestedInteger(object):
  6. # def isInteger(self):
  7. # """
  8. # @return True if this NestedInteger holds a single integer, rather than a nested list.
  9. # :rtype bool
  10. # """
  11. #
  12. # def getInteger(self):
  13. # """
  14. # @return the single integer that this NestedInteger holds, if it holds a single integer
  15. # Return None if this NestedInteger holds a nested list
  16. # :rtype int
  17. # """
  18. #
  19. # def getList(self):
  20. # """
  21. # @return the nested list that this NestedInteger holds, if it holds a nested list
  22. # Return None if this NestedInteger holds a single integer
  23. # :rtype List[NestedInteger]
  24. # """
  25.  
  26. class NestedIterator(object):
  27.  
  28. def __init__(self, nestedList):
  29. """
  30. Initialize your data structure here.
  31. :type nestedList: List[NestedInteger]
  32. """
  33. self.stack = []
  34. self.list = nestedList
  35.  
  36. def next(self):
  37. """
  38. :rtype: int
  39. """
  40. return self.stack.pop()
  41.  
  42. def hasNext(self):
  43. """
  44. :rtype: bool
  45. """
  46. while self.list or self.stack:
  47. if not self.stack:
  48. self.stack.append(self.list.pop(0))
  49. while self.stack and not self.stack[-1].isInteger():
  50. top = self.stack.pop().getList()
  51. for e in top[::-1]:
  52. self.stack.append(e)
  53. if self.stack and self.stack[-1].isInteger():
  54. return True
  55. return False
  56.  
  57. # Your NestedIterator object will be instantiated and called as such:
  58. # i, v = NestedIterator(nestedList), []
  59. # while i.hasNext(): v.append(i.next())  

Python: queue

  1. class NestedIterator(object):
  2.  
  3. def __init__(self, nestedList):
  4. """
  5. Initialize your data structure here.
  6. :type nestedList: List[NestedInteger]
  7. """
  8. self.queue = collections.deque()
  9. def getAll(nests):
  10. for nest in nests:
  11. if nest.isInteger():
  12. self.queue.append(nest.getInteger())
  13. else:
  14. getAll(nest.getList())
  15. getAll(nestedList)
  16.  
  17. def next(self):
  18. """
  19. :rtype: int
  20. """
  21. return self.queue.popleft()
  22.  
  23. def hasNext(self):
  24. """
  25. :rtype: bool
  26. """
  27. return len(self.queue)
  28.  
  29. # Your NestedIterator object will be instantiated and called as such:
  30. # i, v = NestedIterator(nestedList), []
  31. # while i.hasNext(): v.append(i.next())

C++: stack

  1. class NestedIterator {
  2. public:
  3. NestedIterator(vector<NestedInteger> &nestedList) {
  4. for (int i = nestedList.size() - 1; i >= 0; --i) {
  5. s.push(nestedList[i]);
  6. }
  7. }
  8.  
  9. int next() {
  10. NestedInteger t = s.top(); s.pop();
  11. return t.getInteger();
  12. }
  13.  
  14. bool hasNext() {
  15. while (!s.empty()) {
  16. NestedInteger t = s.top();
  17. if (t.isInteger()) return true;
  18. s.pop();
  19. for (int i = t.getList().size() - 1; i >= 0; --i) {
  20. s.push(t.getList()[i]);
  21. }
  22. }
  23. return false;
  24. }
  25.  
  26. private:
  27. stack<NestedInteger> s;
  28. };

C++:deque

  1. class NestedIterator {
  2. public:
  3. NestedIterator(vector<NestedInteger> &nestedList) {
  4. for (auto a : nestedList) {
  5. d.push_back(a);
  6. }
  7. }
  8.  
  9. int next() {
  10. NestedInteger t = d.front(); d.pop_front();
  11. return t.getInteger();
  12. }
  13.  
  14. bool hasNext() {
  15. while (!d.empty()) {
  16. NestedInteger t = d.front();
  17. if (t.isInteger()) return true;
  18. d.pop_front();
  19. for (int i = 0; i < t.getList().size(); ++i) {
  20. d.insert(d.begin() + i, t.getList()[i]);
  21. }
  22. }
  23. return false;
  24. }
  25.  
  26. private:
  27. deque<NestedInteger> d;
  28. };

C++: Recursion

  1. class NestedIterator {
  2. public:
  3. NestedIterator(vector<NestedInteger> &nestedList) {
  4. make_queue(nestedList);
  5. }
  6.  
  7. int next() {
  8. int t = q.front(); q.pop();
  9. return t;
  10. }
  11.  
  12. bool hasNext() {
  13. return !q.empty();
  14. }
  15.  
  16. private:
  17. queue<int> q;
  18. void make_queue(vector<NestedInteger> &nestedList) {
  19. for (auto a : nestedList) {
  20. if (a.isInteger()) q.push(a.getInteger());
  21. else make_queue(a.getList());
  22. }
  23. }
  24. };

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. Tulip Festival(线段树+二分+CDQ+带修改莫队+树套树)

    题目链接 传送门 线段树\(+\)二分思路 思路 比赛看到这题时感觉是一棵线段树\(+\)主席树,然后因为不会带修改主席树就放弃了,最后发现还卡了树套树. 由于本题数据保证序列中相同的数字不会超过20 ...

  2. ajax、axios、fetch 对比

    前言 今天在看到一个比较好的插件,写一个示例时,由于需要请求在线数据,官方给的是用 $.get(),就为了一个示例使用 JQuery 没必要. 又找了找,发现有用 fecth 的,挺方便,这里就做一个 ...

  3. 项目Beta冲刺 - 凡事预则立

    课程: 软件工程1916|W(福州大学) 作业要求: 项目Beta冲刺 团队名称: 火鸡堂 作业目标: 尽力交付 火鸡堂 队员学号 队员姓名 博客地址 备注 221600111 彼术向 http:// ...

  4. 查看mysql执行时间

    mysql的 profiling不是默认打开的 查看profiling是否找开 mysql> show variables like "%pro%"; +---------- ...

  5. SUID提权

    查看tmp目录权限 ll -d /tmp 切换到tmp目录 cd /tmp 创建一个exploit目录 mkdir exploit 查看ping命令带suid权限 ll /bin/ping 创建tar ...

  6. MySQL server has gone away && Lost connection to MySQL server during query

    问题一.MySQL server has gone away ##### peewee from peewee import * from peewee import __exception_wrap ...

  7. VisualStudio 2019 Serials

    9DP6T-9AGWG-KWV33-9MPC8-JDCVF 7G2HE-JR8KL-ABB9D-Y7789-GLNFL U2PWU-H7D9H-69T3B-JEYC2-3R2NG R8R8P-MTT6 ...

  8. vue+elementUI完成注册及登陆

    1. vue怎么引入和配置使用element-ui框架 1.1 使用vue-cli脚手架工具创建一个vue项目 vue init webpack pro01 1.2 npm安装elementUI cd ...

  9. JavaScript高级程序编程(三)

    2017-06-24 更新 北京连续三天下雨啦 乘性操作符   1.ECMA中定义了三种操作符,乘法 除法 和求模 并与其他语言相应操作符相同,再计算之前如果不是数值,会先去调用number()方法转 ...

  10. Angular2发送HTTP请求SpringBoot后台跨域问题解决

    Angular通过http发送post请求至SpringBoot的Controller,由于同源策略的保护,遇到跨域问题: • 源(origin)就是协议(http).域名(localhost)和端口 ...