码迷,mamicode.com
首页 > 其他好文 > 详细

Peeking Iterator

时间:2016-08-06 09:40:50      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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.

 1 class PeekingIterator implements Iterator<Integer> {
 2     private Integer next; //cache the next peek
 3     private Iterator<Integer> iter;
 4     
 5     public PeekingIterator(Iterator<Integer> iterator) {
 6         // initialize any member here.
 7         iter = iterator;
 8         if (iter.hasNext()) {
 9             next = iter.next();
10         }
11     }
12  
13     // Returns the next element in the iteration without advancing the iterator.
14     public Integer peek() {
15         return next;
16     }
17  
18     // hasNext() and next() should behave the same as in the Iterator interface.
19     // Override them if needed.
20     @Override
21     public Integer next() {
22         Integer ret = next;
23         next = iter.hasNext() ? iter.next() : null; 
24         return ret;
25     }
26  
27     @Override
28     public boolean hasNext() {
29         return next != null;
30     }
31 }

 

Peeking Iterator

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5743258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!