zoukankan      html  css  js  c++  java
  • [leetcode]341. Flatten Nested List Iterator展开嵌套列表的迭代器

    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:

    Input: [[1,1],2,[1,1]]
    Output: [1,1,2,1,1]
    Explanation: By calling next repeatedly until hasNext returns false, 
                 the order of elements returned by next should be: [1,1,2,1,1].

    Example 2:

    Input: [1,[4,[6]]]
    Output: [1,4,6]
    Explanation: By calling next repeatedly until hasNext returns false, 
                 the order of elements returned by next should be: [1,4,6].

    题目

    将Nested List展平,像访问一个一维列表一样访问嵌套列表。

    思路

    queue

    代码

     1 public class NestedIterator implements Iterator<Integer> {
     2     
     3     Queue<Integer> queue;
     4     
     5     public NestedIterator(List<NestedInteger> nestedList) {
     6        queue = new LinkedList<>();
     7        helper(nestedList); 
     8     }
     9 
    10     @Override
    11     public Integer next() {
    12         return queue.poll();
    13     }
    14 
    15     @Override
    16     public boolean hasNext() {
    17         return !queue.isEmpty();
    18     }
    19     private void helper(List<NestedInteger> nestedList){
    20         for(NestedInteger n:nestedList){
    21             if(n.isInteger()){
    22                 queue.add(n.getInteger());
    23             }else{
    24                 helper(n.getList());
    25             }
    26         }
    27     }
    28 }
  • 相关阅读:
    背景透明度IE兼容性代码
    酷站收藏
    洛谷P1142 轰炸 数学
    洛谷P1282 多米诺骨牌
    洛谷P1247 取火柴游戏 数学题 博弈论
    洛谷P1135 奇怪的电梯 广搜
    洛谷P1077 摆花 动态规划
    洛谷P1161 开灯 数学
    洛谷P1154 奶牛分厩 数学
    洛谷P2147 [SDOI2008]Cave 洞穴勘测 Link-Cut Tree LCT
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9828196.html
Copyright © 2011-2022 走看看