[LeetCode][Java]Peeking Iterator

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?

https://leetcode.com/problems/peeking-iterator/

 

 

 


 
 
 
给Iterator增加一个peek方法。
比较简单,开一个变量存一个next的值,维护好这个变量就行了。
 1 //Java Iterator interface reference:
 2 //https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
 3 class PeekingIterator implements Iterator<Integer> {
 4 
 5     private Iterator<Integer> it;
 6     private boolean peeked = false;
 7     private Integer top; 
 8 
 9     public PeekingIterator(Iterator<Integer> iterator) {
10         // initialize any member here.
11         this.it = iterator;
12     }
13 
14  // Returns the next element in the iteration without advancing the iterator.
15     public Integer peek() {
16         if(!peeked){
17             top = it.next();
18             peeked = true;
19         }
20         return top;
21     }
22 
23     // hasNext() and next() should behave the same as in the Iterator interface.
24     // Override them if needed.
25     @Override
26     public Integer next() {
27         if(!peeked){
28             return it.next();
29         }else{
30             peeked = false;
31             return top;
32         }
33     }
34 
35     @Override
36     public boolean hasNext() {
37         if(peeked){
38             return true;
39         }else{
40             return it.hasNext();
41         }
42     }
43     
44 }

 

 
 
posted @ 2015-09-27 14:31  `Liok  阅读(503)  评论(0编辑  收藏  举报