|
| 1 | +package com.stevesun.solutions; |
| 2 | + |
| 3 | +import java.util.Iterator; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.Queue; |
| 6 | + |
| 7 | +/** |
| 8 | + * 284. Peeking Iterator |
| 9 | + * |
| 10 | + * 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(). |
| 11 | +
|
| 12 | + Here is an example. Assume that the iterator is initialized to the beginning of the queue: [1, 2, 3]. |
| 13 | +
|
| 14 | + Call next() gets you 1, the first element in the queue. |
| 15 | +
|
| 16 | + Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. |
| 17 | +
|
| 18 | + You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false. |
| 19 | +
|
| 20 | + Follow up: How would you extend your design to be generic and work with all types, not just integer? |
| 21 | + */ |
| 22 | +public class _284 { |
| 23 | + public static class PeekingIterator implements Iterator<Integer> { |
| 24 | + |
| 25 | + private Queue<Integer> queue; |
| 26 | + public PeekingIterator(Iterator<Integer> iterator) { |
| 27 | + // initialize any member here. |
| 28 | + queue = new LinkedList<>(); |
| 29 | + while (iterator.hasNext()) { |
| 30 | + queue.add(iterator.next()); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Returns the next element in the iteration without advancing the iterator. |
| 35 | + public Integer peek() { |
| 36 | + return queue.peek(); |
| 37 | + } |
| 38 | + |
| 39 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 40 | + // Override them if needed. |
| 41 | + @Override |
| 42 | + public Integer next() { |
| 43 | + return queue.poll(); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public boolean hasNext() { |
| 48 | + return !queue.isEmpty(); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments