284. Peeking Iterator
本来的Iterator类里面是自带next()和hasNext()的,但是现在加了peek()之后会调用一次iterator.next(),然后iterator的顺序就乱了。
所以一旦被peek过我们就需要把这个被next()弹出的元素记录下来,如果再调用next就返回这个临时的元素,再调用peek就还返回这个元素,再调用hasNext就返回有没有被peek过或者hasNext()本身
1 class PeekingIterator implements Iterator<Integer> { 2 private Iterator<Integer> it; 3 private Integer next; 4 private boolean isPeeked; 5 6 public PeekingIterator(Iterator<Integer> iterator) { 7 // initialize any member here. 8 it = iterator; 9 isPeeked = false; 10 } 11 12 // Returns the next element in the iteration without advancing the iterator. 13 public Integer peek() { 14 if (isPeeked) { 15 return next; 16 } else { 17 isPeeked = true; 18 next = it.next(); 19 return next; 20 } 21 } 22 23 // hasNext() and next() should behave the same as in the Iterator interface. 24 // Override them if needed. 25 @Override 26 public Integer next() { 27 Integer res; 28 if(isPeeked) { 29 res = next; 30 } else { 31 res = it.next(); 32 } 33 isPeeked = false; 34 return res; 35 } 36 37 @Override 38 public boolean hasNext() { 39 return isPeeked? true: it.hasNext(); 40 } 41 }
bug记录:
peek()本身的时候也要检查有没有被peek过,否则会一直往后面看去,就会丢失元素