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

LeetCode——Peeking Iterator

时间:2015-10-12 23:59:37      阅读:400      评论:0      收藏:0      [点我收藏+]

标签:

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.Show More Hint 

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

Credits:
Special thanks to @porker2008 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<Integer> {
 4     
 5     private Iterator<Integer> it;
 6     
 7     private Integer top = null;
 8 
 9     public PeekingIterator(Iterator<Integer> 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     @Override
29     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     @Override
42     public boolean hasNext() {
43         if(top != null) {
44             return true;
45         }
46         return it.hasNext();
47     }
48 }

 

LeetCode——Peeking Iterator

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4873015.html

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