Flatten Nested List Iterator

 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 Deque<Integer> flatten;
20     public NestedIterator(List<NestedInteger> nestedList) {
21         flatten = new LinkedList<>();
22         getFlatten(nestedList);
23     }
24     
25     private void getFlatten(List<NestedInteger> nestedList) {
26         for (int i = 0; i < nestedList.size(); i++) {
27             if (nestedList.get(i).isInteger()) {
28                 flatten.offer(nestedList.get(i).getInteger());
29             } else {
30                 getFlatten(nestedList.get(i).getList());
31             }
32         }
33     }
34 
35     @Override
36     public Integer next() {
37         return flatten.pollFirst();
38     }
39 
40     @Override
41     public boolean hasNext() {
42         return flatten.size() > 0;
43     }
44 }
45 
46 /**
47  * Your NestedIterator object will be instantiated and called as such:
48  * NestedIterator i = new NestedIterator(nestedList);
49  * while (i.hasNext()) v[f()] = i.next();
50  */

 

转载于:https://www.cnblogs.com/shuashuashua/p/5631739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值