Skip to content

Commit c5e5f49

Browse files
committed
284 (1) add solution
1 parent 31da148 commit c5e5f49

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy