File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 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+ import java .util .Iterator ;
20+
21+ /** see test {@link _284_PeekingIterator.SolutionTest } */
22+ public class Solution implements Iterator <Integer > {
23+
24+ private Integer cache ;
25+
26+ private Iterator <Integer > _iter ;
27+
28+ public Solution (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+ public Integer peek () {
36+ if (cache == null ) {
37+ cache = _iter .next ();
38+ }
39+ return cache ;
40+ }
41+
42+ // hasNext() and next() should behave the same as in the Iterator interface.
43+ // Override them if needed.
44+ @ Override
45+ public Integer next () {
46+ if (cache != null ) {
47+ Integer next = cache ;
48+ cache = null ;
49+ return next ;
50+ } else {
51+ return _iter .next ();
52+ }
53+ }
54+
55+ @ Override
56+ public boolean hasNext () {
57+ return _iter .hasNext () || cache != null ;
58+ }
59+
60+ }
You can’t perform that action at this time.
0 commit comments