p284

LeetCode p284 Peeking Iterator 题解

1.题目:

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().

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

题意:

实现一个迭代器的数据结构。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {

Iterator<Integer> iterator;
ArrayList<Integer> arrayList;

public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
this.iterator = iterator;
arrayList = new ArrayList<Integer>();

}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
int a = 0;
if (arrayList.size() > 0) {
a = arrayList.get(0);

} else {

a = iterator.next();
arrayList.add(a);
}
return a;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
int a = 0;
if (arrayList.size() > 0) {
a = arrayList.get(0);

arrayList.remove(0);
} else {

a = iterator.next();
}
return a;
}

@Override
public boolean hasNext() {
return iterator.hasNext()||(arrayList.size() > 0);
}
}

4.一些总结: