Topic:
Given an Iterator class interface with methods: next()
hasNext()
and, design and implement a Peekingiterator c5/> 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.
Follow Up:how would you extend your design to is generic and work with all types, not just integer?
test instructions and analysis: The iterator iterator interface has the next and Hasnext methods, Peekingiterator implements the iterator interface, requires implementing a Peek method, returns the next element, but does not move to the next element. The initialization is then moved backwards, then the value of next () is saved with an intermediate variable res in next () and then returned to Res.
Code:
//Java Iterator Interface Reference:// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.htmlclassPeekingiteratorImplementsIterator<integer> { PrivateInteger next =NULL; PrivateIterator<integer>ITER; PublicPeekingiterator (iterator<integer>iterator) { //Initialize any member here.ITER =iterator; if(Iter.hasnext ()) Next=Iter.next (); } //Returns the next element in the iteration without advancing the iterator. PublicInteger Peek () {returnNext; } //Hasnext () and next () should behave the same as in the Iterator interface. //Override them if needed.@Override Publicinteger Next () {integer res=Next; Next= Iter.hasnext ()? Iter.next ():NULL; returnRes; } @Override Public BooleanHasnext () {returnNext! =NULL; }}
[Leetcode] 284. Peeking Iterator Java