284. Peeking Iterator

Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

  • PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator.
  • int next() Returns the next element in the array and moves the pointer to the next element.
  • boolean hasNext() Returns true if there are still elements in the array.
  • int peek() Returns the next element in the array without moving the pointer.

Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

使用队列储存迭代器里的数据,根据需要返回队列里的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator implements Iterator<Integer> {
Queue<Integer> q;
public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
q = new LinkedList<>();
while(iterator.hasNext()){
q.add(iterator.next());
}
}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return q.peek();
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
return q.poll();
}

@Override
public boolean hasNext() {
return !q.isEmpty();
}
}
Author

Xander

Posted on

2022-04-25

Updated on

2022-04-24

Licensed under

Comments