博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode——Peeking Iterator
阅读量:6639 次
发布时间:2019-06-25

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

Description:

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().


Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint:

  1. Think of "looking ahead". You want to cache the next element.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Credits:

Special thanks to  for adding this problem and creating all test cases.

就是利用Java中的Iterator接口来实现一个类,主要是peek()方法的实现与API中的不同,可以在peek()和next()中同时使用Iterator.next()来实现。

设置一个top来保存当前值。

 

1 // Java Iterator interface reference: 2 // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html 3 class PeekingIterator implements Iterator
{ 4 5 private Iterator
it; 6 7 private Integer top = null; 8 9 public PeekingIterator(Iterator
iterator) {10 // initialize any member here.11 it = iterator;12 }13 14 // Returns the next element in the iteration without advancing the iterator.15 public Integer peek() {16 Integer peek;17 if(top != null) {18 peek = top;19 }20 else {21 peek = top = next();22 }23 return peek;24 }25 26 // hasNext() and next() should behave the same as in the Iterator interface.27 // Override them if needed.28 @Override29 public Integer next() {30 Integer next = 0;31 if(top != null) {32 next = top;33 top = null;34 }35 else {36 next = it.next();37 }38 return next;39 }40 41 @Override42 public boolean hasNext() {43 if(top != null) {44 return true;45 }46 return it.hasNext();47 }48 }

 

转载地址:http://weivo.baihongyu.com/

你可能感兴趣的文章
服务程序应用的安装方法汇总
查看>>
【ionic App问题总结系列】ionic 如何更新app版本
查看>>
twitter storm源码走读之3--topology提交过程分析
查看>>
拥抱新技术的一点思考
查看>>
Android 设计一个菱形形状的Imageview组件.
查看>>
Dynamics CRM JS的调试的弊端解决办法
查看>>
Sublime Text 3 常用快捷键
查看>>
MongoDB
查看>>
PHP 验证密码是否为联系的6位数字(适用于支付密码的验证)
查看>>
animation渐进实现点点点等待效果实例页面
查看>>
如何在sumbline运行python文件
查看>>
UITextView实现占位文字的两种方法
查看>>
问题MySQL server has gone away
查看>>
Vue Router使用范例
查看>>
SpriteKit-SKView
查看>>
windows xp通过VNC viewer远程连接RHEL5桌面
查看>>
ECMAScript5中数组方法
查看>>
一个WPF只能输入数字的行为。
查看>>
CentOS平台部署vsftp(基于虚拟用户)
查看>>
Linux常用命令
查看>>