Topic:
Given an Iterator class interface with methods: next() hasNext() and, design and implement a Peekingiterator c2/> operation--it essentially peek () at the element, that would be a returned by the next call to next ().
Here's an example. Assume that the iterator are initialized to the beginning of the list: [1, 2, 3] .
Call next() gets your 1, the first element in the list.
Now your call peek() and it returns 2, the next element. Calling after that next() still return 2.
next()the final time and it returns 3, the last element. Calling after that hasNext() should return false.
Tips:
This problem I started with a queue to do, and then saw the discussion plate only found that in fact, Iterator class is a copy of the constructor: Iterator (const iterator& ITER);
In this case, using the instance returned by the copy constructor, there is no need to worry about affecting the cursor position.
Code:
//Below are the interface for Iterator, which are already defined for you.//**do not** Modify the interface for Iterator.classIterator {structData; Data*data; Public: Iterator (Constvector<int>&nums); Iterator (Constiterator&ITER); Virtual~Iterator (); //Returns the next element in the iteration. intnext (); //Returns True if the iteration have more elements. BOOLHasnext ()Const;};classPeekingiterator: PublicIterator { Public: Peekingiterator (Constvector<int>&nums): Iterator (nums) {//Initialize any member here. //**do not** Save a copy of Nums and manipulate it directly. //You should only use the Iterator interface methods. } //Returns the next element in the iteration without advancing the iterator. intPeek () {returnIterator (* 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 (); }Private:};
"Leetcode" 284. Peeking Iterator