classPeekingIterator:publicIterator{public:PeekingIterator(constvector<int>&nums):Iterator(nums){}// Returns the next element in the iteration without advancing the iterator.intpeek(){// Iterator(*this) makes a copy of current iterator, then call next on the// Copied iterator to get the next value without affecting current iteratorreturnIterator(*this).next();}// hasNext() and next() should behave the same as in the Iterator interface.// Override them if needed.intnext(){returnIterator::next();}boolhasNext()const{returnIterator::hasNext();}};
// Java Iterator interface reference:// Https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.htmlclassPeekingIteratorimplementsIterator<Integer>{publicPeekingIterator(Iterator<Integer>iterator){this.iterator=iterator;buffer=iterator.hasNext()?iterator.next():null;}// Returns the next element in the iteration without advancing the iterator.publicIntegerpeek(){returnbuffer;}// hasNext() and next() should behave the same as in the Iterator interface.// Override them if needed.@OverridepublicIntegernext(){Integernext=buffer;buffer=iterator.hasNext()?iterator.next():null;returnnext;}@OverridepublicbooleanhasNext(){returnbuffer!=null;}privateIterator<Integer>iterator;privateIntegerbuffer;}
classPeekingIterator:def__init__(self,iterator:Iterator):self.iterator=iteratorself.buffer=self.iterator.next()ifself.iterator.hasNext()elseNonedefpeek(self)->int:""" Returns the next element in the iteration without advancing the iterator. """returnself.bufferdefnext(self)->int:next=self.bufferself.buffer=self.iterator.next()ifself.iterator.hasNext()elseNonereturnnextdefhasNext(self)->bool:returnself.bufferisnotNone