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:
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 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * public interface NestedInteger {
 5  *
 6  *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 7  *     public boolean isInteger();
 8  *
 9  *     // @return the single integer that this NestedInteger holds, if it holds a single integer
10  *     // Return null if this NestedInteger holds a nested list
11  *     public Integer getInteger();
12  *
13  *     // @return the nested list that this NestedInteger holds, if it holds a nested list
14  *     // Return null if this NestedInteger holds a single integer
15  *     public List<NestedInteger> getList();
16  * }
17  */
18 public class NestedIterator implements Iterator<Integer> {
19     private List<Integer> flattenedList;
20     private Iterator<Integer> it;
21 
22     public NestedIterator(List<NestedInteger> nestedList) {
23         flattenedList = new LinkedList<Integer>();
24         flatten(nestedList);
25         it = flattenedList.iterator();
26     }
27     private void flatten(List<NestedInteger> nestedList) {
28         for (NestedInteger i : nestedList) {
29             if (i.isInteger()) {
30                 flattenedList.add(i.getInteger());
31             } else {
32                 flatten(i.getList());
33             }
34         }
35     }
36 
37     @Override
38     public Integer next() {
39         return it.next();
40     }
41 
42     @Override
43     public boolean hasNext() {
44         return it.hasNext();
45     }
46 }
47 
48 /**
49  * Your NestedIterator object will be instantiated and called as such:
50  * NestedIterator i = new NestedIterator(nestedList);
51  * while (i.hasNext()) v[f()] = i.next();
52  */
复制代码

 

 

 

 

 
posted @   daniel456  阅读(112)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示