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.
Analysis:
This is a design problem, which requires you familiar with the Object-Oriented basics.
In C++, calling base class methods within derived class can be done using "baseclassName::baseclassMethod()"
In python, usually we use "super(BaseClassName, self)" to do so. However, in this problem, the python interface does NOT provide the inheritance of class Iterator, but use the Iterator as a class member, therefore just call a member's function is enough.
Back to the question, we have to notice that:
- The peek() method could be called multiple times but we can only go next() at the first time.
- The next() method could be called before or after peek(). We need a flag and a value to store the state if the peek() method has been called or not (as well as the value).
- To check the hasNext(), we have to check the stored peek value, because if we peek() the last value, it is called the next() method of base class resulting in the last value is poped from the array but only exists in our stored peeked_value. So the hasNext() method of baseclass will return a false, but actually we just "peeked" the next value.
Nice post. Thanks for posting. Keep sharing more and more SEO Training
ReplyDeleteJava Training
python Training
Salesforce Training
Tableau Training
AWS training
Dot Net Training
DevOps Training
Selenium Training
ReplyDeletewhy is microsoft word not responding
why is word not responding
microsoft word not responding
microsoft word keeps crashing mac
microsoft word not opening
why my canon printer is printing blank pages
why does my canon printer print blank pages
canon printer printing blank pages