Skip to content

Commit 7638268

Browse files
refactor 284
1 parent 00706a3 commit 7638268

File tree

1 file changed

+27
-23
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-23
lines changed

src/main/java/com/fishercoder/solutions/_284.java

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
/**
88
* 284. Peeking Iterator
99
*
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().
10+
* Given an Iterator class interface with methods: next() and hasNext(),
11+
* design and implement a PeekingIterator that support
12+
* the peek() operation -- it essentially peek() at the element that will be returned by the next call to next().
1113
1214
Here is an example. Assume that the iterator is initialized to the beginning of the queue: [1, 2, 3].
1315
@@ -20,33 +22,35 @@ You call next() the final time and it returns 3, the last element. Calling hasNe
2022
Follow up: How would you extend your design to be generic and work with all types, not just integer?
2123
*/
2224
public class _284 {
23-
public static class PeekingIterator implements Iterator<Integer> {
25+
public static class Solution1 {
26+
public static class PeekingIterator implements Iterator<Integer> {
2427

25-
private Queue<Integer> queue;
28+
private Queue<Integer> queue;
2629

27-
public PeekingIterator(Iterator<Integer> iterator) {
28-
// initialize any member here.
29-
queue = new LinkedList<>();
30-
while (iterator.hasNext()) {
31-
queue.add(iterator.next());
30+
public PeekingIterator(Iterator<Integer> iterator) {
31+
// initialize any member here.
32+
queue = new LinkedList<>();
33+
while (iterator.hasNext()) {
34+
queue.add(iterator.next());
35+
}
3236
}
33-
}
3437

35-
// Returns the next element in the iteration without advancing the iterator.
36-
public Integer peek() {
37-
return queue.peek();
38-
}
38+
// Returns the next element in the iteration without advancing the iterator.
39+
public Integer peek() {
40+
return queue.peek();
41+
}
3942

40-
// hasNext() and next() should behave the same as in the Iterator interface.
41-
// Override them if needed.
42-
@Override
43-
public Integer next() {
44-
return queue.poll();
45-
}
43+
// hasNext() and next() should behave the same as in the Iterator interface.
44+
// Override them if needed.
45+
@Override
46+
public Integer next() {
47+
return queue.poll();
48+
}
4649

47-
@Override
48-
public boolean hasNext() {
49-
return !queue.isEmpty();
50+
@Override
51+
public boolean hasNext() {
52+
return !queue.isEmpty();
53+
}
5054
}
5155
}
52-
}
56+
}

0 commit comments

Comments
 (0)