|
| 1 | +/** |
| 2 | + * Time : O() ; Space: O() |
| 3 | + * @tag : Design |
| 4 | + * @by : Steven Cooks |
| 5 | + * @date: Sep 30, 2015 |
| 6 | + *************************************************************************** |
| 7 | + * Description: |
| 8 | + * |
| 9 | + * Given an Iterator class interface with methods: next() and hasNext(), |
| 10 | + * design and implement a PeekingIterator that support the peek() operation |
| 11 | + * -- it essentially peek() at the element that will be returned by the next |
| 12 | + * call to next(). |
| 13 | + * |
| 14 | + *************************************************************************** |
| 15 | + * {@link https://leetcode.com/problems/peeking-iterator/ } |
| 16 | + */ |
| 17 | +package_284_PeekingIterator; |
| 18 | + |
| 19 | +importjava.util.Iterator; |
| 20 | + |
| 21 | +/** see test {@link _284_PeekingIterator.SolutionTest } */ |
| 22 | +publicclassSolutionimplementsIterator<Integer> { |
| 23 | + |
| 24 | +privateIntegercache; |
| 25 | + |
| 26 | +privateIterator<Integer>_iter; |
| 27 | + |
| 28 | +publicSolution(Iterator<Integer>iterator) { |
| 29 | +// initialize any member here. |
| 30 | +cache =null; |
| 31 | +_iter =iterator; |
| 32 | + } |
| 33 | + |
| 34 | +// Returns the next element in the iteration without advancing the iterator. |
| 35 | +publicIntegerpeek() { |
| 36 | +if (cache ==null) { |
| 37 | +cache =_iter.next(); |
| 38 | + } |
| 39 | +returncache; |
| 40 | + } |
| 41 | + |
| 42 | +// hasNext() and next() should behave the same as in the Iterator interface. |
| 43 | +// Override them if needed. |
| 44 | +@Override |
| 45 | +publicIntegernext() { |
| 46 | +if (cache !=null) { |
| 47 | +Integernext =cache; |
| 48 | +cache =null; |
| 49 | +returnnext; |
| 50 | + }else { |
| 51 | +return_iter.next(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | +@Override |
| 56 | +publicbooleanhasNext() { |
| 57 | +return_iter.hasNext() ||cache !=null; |
| 58 | + } |
| 59 | + |
| 60 | +} |