您的位置:首页 > 其它

LeetCode Peeking Iterator

2016-01-11 12:16 351 查看
Description:

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.

Solution:

开始没反应过来,后来发现只要建立一个类似于缓存机制的东西即可。

在这里,就用peekFlag和peekNum来代表是否已经peek过,已经peek的数值。

<span style="font-size:18px;">import java.util.*;

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> {
Iterator<Integer> ite;
boolean peekFlag = false;
Integer peekNum;

public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
ite = iterator;
peekFlag = false;
}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (!peekFlag) {
peekFlag = true;
peekNum = ite.next();
}
return peekNum;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (peekFlag) {
peekFlag = false;
return peekNum;
}
return ite.next();
}

@Override
public boolean hasNext() {
return peekFlag || ite.hasNext();
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: