Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc5e5f49

Browse files
committed
284 (1) add solution
1 parent31da148 commitc5e5f49

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+
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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp