博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 341: Flatten Nested List Iterator
阅读量:7194 次
发布时间:2019-06-29

本文共 1802 字,大约阅读时间需要 6 分钟。

/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * *     // @return true if this NestedInteger holds a single integer, rather than a nested list. *     public boolean isInteger(); * *     // @return the single integer that this NestedInteger holds, if it holds a single integer *     // Return null if this NestedInteger holds a nested list *     public Integer getInteger(); * *     // @return the nested list that this NestedInteger holds, if it holds a nested list *     // Return null if this NestedInteger holds a single integer *     public List
getList(); * } */public class NestedIterator implements Iterator
{ Stack
stack; public NestedIterator(List
nestedList) { stack = new Stack<>(); pushData(nestedList); } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { while(!stack.isEmpty()) { if (stack.peek().isInteger()) { return true; } pushData(stack.pop().getList()); } return false; } private void pushData(List
nestedList) { for (int i = nestedList.size() - 1; i >= 0; i--) { stack.push(nestedList.get(i)); } }}/** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i = new NestedIterator(nestedList); * while (i.hasNext()) v[f()] = i.next(); */

 

1 Remember : Always make integer validation at hasNext() since it is too late to validate it at next().

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

你可能感兴趣的文章
【强化学习篇】--强化学习从初识到应用
查看>>
获取图片
查看>>
过滤器
查看>>
软件工程个人作业02(四则运算)
查看>>
jQuery自动完成点击html元素
查看>>
关于随机数
查看>>
《世界是数字的》读书笔记
查看>>
LeetCode开心刷题第七天——13RomanToInteger14 Longest Common Prefix
查看>>
php中直接执行mysqli_init()也是报Property access is not allowed yet的错误。
查看>>
领导讲话笔记 记录(游戏编辑器)
查看>>
"ApplicationDbContext"(泛指之类的数据库上下文模型)上下文的模型已在数据库创建后发生更改。请考虑使用 Code First 迁移更新数据库。...
查看>>
Django Model 基础数据库操作应用
查看>>
Java ConcurrentModificationException异常原因和解决方法[转载]
查看>>
单例模式防止反射和反序列化
查看>>
聚集索引和非聚集索引的区别
查看>>
搭建前端监控系统(备选)用户行为统计和监控篇(如何快速定位线上问题)...
查看>>
linux常用命令
查看>>
Django 序列化
查看>>
[SQL]躺着也中枪的datetime类型
查看>>
Eclipse设置Tab键为空格
查看>>