前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >How to design and implement a deep iterator?

How to design and implement a deep iterator?

作者头像
包子面试培训
发布2018-04-20 16:14:42
5900
发布2018-04-20 16:14:42
举报
文章被收录于专栏:包子铺里聊IT

包子IT面试培训 助你拿到理想的offer!

Question:

Write a deep iterator to iterate through a list of objects or integer which could be another list or integer. This is frequently asked by LinkedIn, Twitter and Hulu.

For example, this collection contains Integer or another collection. L means it is a collection that contains either integer or another L.

----> 5

|

---- 3 -> 4 -> L -> 6

|

1 -> 2 -> L -> 7-> 8

We would expect an iterator to loop through it will print out 1, 2, 3, 4, 5, 6, 7, 8

Analysis:

The input is a list of objects which could be another list or a integer. The input is kind of similar to a tree or a forest data structure. Here we are asked to implement two functions of a iterator, hasNext and next. (Iterator in Java has hasNext(), next() and remove(). ) So we need to iterate through the tree. Using recursion it is easy, but here we need to convert a recursion problem to a iteration problem. So we need a stack to keep track of the levels we are in the iteration.

The code is like following.

....

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2014-08-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 包子铺里聊IT 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 包子IT面试培训 助你拿到理想的offer!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档