• [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 }
  • 相关阅读:
    [蓝桥杯][基础训练]报时助手
    [蓝桥杯][基础训练]分解质因数
    [蓝桥杯][基础训练]2n皇后问题
    [啊哈算法]我要做月老
    [啊哈算法]关键道路(图的割边)
    [啊哈算法]重要城市(图的割点)
    并查集
    栈数组与栈链表代码实现

    循环链表
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9828196.html
Copyright © 2020-2023  润新知