题目链接:https://leetcode.com/problems/peeking-iterator/
题目:
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.
Hint:
peek()
before next()
vs next()
before peek()
.Follow up: How would you extend your design to be generic and work with all types, not just integer?
思路:
缓存下一个元素用于peek操作,同时注意要用一个hasNext变量表示是否有缓存元素。否则在hasnext方法中如果用iterator的hasnext由于缓存一个元素提前用了一次next导致hasnext结果不对。比如[1,2,3],hasnext,next,next,hasnext会返回false而正确结果应为true。
算法:
class PeekingIterator implements Iterator<Integer> { Iterator<Integer> iterator; int nextNum = 0; //缓存下一个元素 boolean hasNext = true; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. this.iterator = iterator; if (iterator.hasNext()) { //缓存第一个元素 hasNext = true; nextNum = iterator.next(); } else { hasNext = false; } } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { return nextNum; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { int result = 0; result = nextNum; if (iterator.hasNext()) { //缓存下一个元素 hasNext = true; nextNum = iterator.next(); } else { hasNext = false; } return result; } @Override public boolean hasNext() { return hasNext; } }