|
9 | 9 | Assume that the iterator is initialized to the beginning of the list: [1,2,3]. |
10 | 10 |
|
11 | 11 | Call next() gets you 1, the first element in the list. |
12 | | -Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. |
13 | | -You call next() the final time and it returns 3, the last element. |
| 12 | +Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. |
| 13 | +You call next() the final time and it returns 3, the last element. |
14 | 14 | Calling hasNext() after that should return false. |
15 | 15 | ``` |
16 | 16 |
|
@@ -62,4 +62,40 @@ class PeekingIterator implements Iterator<Integer> { |
62 | 62 | return it.hasNext(); |
63 | 63 | } |
64 | 64 | } |
65 | | -``` |
| 65 | +``` |
| 66 | + |
| 67 | +### Second time |
| 68 | +1. I used a queue to save the values that can be gotten from the iterator. |
| 69 | +2. peek means getting the first value in the queue. |
| 70 | +3. next means poll the queue. |
| 71 | +```Java |
| 72 | +// Java Iterator interface reference: |
| 73 | +// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html |
| 74 | +class PeekingIterator implements Iterator<Integer> { |
| 75 | + Iterator<Integer> it = null; |
| 76 | + LinkedList<Integer> record = null; |
| 77 | + public PeekingIterator(Iterator<Integer> iterator) { |
| 78 | + // initialize any member here. |
| 79 | + this.it = iterator; |
| 80 | + record = new LinkedList<>(); |
| 81 | + while(it.hasNext()){ |
| 82 | + int num = it.next(); |
| 83 | + this.record.add(num); |
| 84 | + } |
| 85 | + } |
| 86 | + // Returns the next element in the iteration without advancing the iterator. |
| 87 | + public Integer peek() { |
| 88 | + return record.get(0); |
| 89 | + } |
| 90 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 91 | + // Override them if needed. |
| 92 | + @Override |
| 93 | + public Integer next() { |
| 94 | + return record.poll(); |
| 95 | + } |
| 96 | + @Override |
| 97 | + public boolean hasNext() { |
| 98 | + return this.record.size() > 0; |
| 99 | + } |
| 100 | +} |
| 101 | +``` |
0 commit comments