284. Peeking Iterator
作者:互联网
This is a Iterator problem too, the soltuion is:
1. keep a variable, nextInt, to store the potential next Integer.
2. when peek(), if the nextInt is not null, then just return it, otherwise, we must call next(), and store the next integer to nextInt.
3. When next(), if the nextInt is not null, then we need to make the nextInt to null, that means, the nextInt has been used. and then return the nextInt's value. Otherwise, return next();
class PeekingIterator implements Iterator<Integer> { private Iterator<Integer> it; private Integer nextInt = null; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. this.it = iterator; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if(nextInt == null){ nextInt = it.next(); } return nextInt; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if(nextInt!=null){ Integer temp = nextInt; nextInt = null; return temp; }else return it.next(); } @Override public boolean hasNext() { if(nextInt!=null) return true; else return it.hasNext(); } }
标签:return,Iterator,next,nextInt,Peeking,Integer,null,284 来源: https://www.cnblogs.com/feiflytech/p/15863824.html