题目链接
法一
public class Solution284 implements Iterator<Integer> {
private AtomicReference<Integer> cache = new AtomicReference<>(null);
private Iterator<Integer> iter;
public Solution284(Iterator<Integer> iterator) {
this.iter = iterator;
cache.set(iter.hasNext() ? iter.next() : null);
}
public Integer peek() {
return cache.get();
}
@Override
public Integer next() {
return cache.getAndSet(iter.hasNext() ? iter.next() : null);
}
@Override
public boolean hasNext() {
return cache.get() != null;
}
}
本地测试
lay.showTitle(284);
List<Integer> list284 = Arrays.asList(1, 2, 3);
Iterator<Integer> iterator284 = list284.iterator();
Solution284 sol284 = new Solution284(iterator284);
System.out.println(list284);
System.out.println(sol284.next());
System.out.println(sol284.peek());
System.out.println(sol284.next());
System.out.println(sol284.next());
System.out.println(sol284.hasNext());