leetcode Peeking Iterator

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.
  2. Is one variable sufficient? Why or why not?
  3. Test your design with call order of peek() before next() vs next() before peek().
  4. For a clean implementation, check out Google’s guava library source code.

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

传送门: leetcode Peeking Iterator

题意:

已经给定了Iterator接口

  • next()
  • hasNext()

让你在此基础上实现PeekingIterator

  • peek():返回下一个元素,但指针不移动到下一个
  • next(): 移动到下一个元素x并返回x
  • hasNext() :返回有下一个元素

思路:

分语言而定,详见代码。

 

C++

定义peek()方法,而peek可以新建一个临时对象,返回其下一个即可。

至于next 和 hasNext直接用父类的方法即可。

 

Java

建一个成员变量cur,记录下一个指针指向的值。

  • peek: 直接返回cur
  • next:  res = cur , 并 判断是否有下一个,若有则赋值为iterator.next,否则null
  • hasNext: 判断cur是否为null

 

Python

同java

 

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Peeking Iterator
本文地址:https://www.hrwhisper.me/leetcode-peeking-iterator/

听说长得好看的已经打赏了

Leetcode , , , , , . permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *