Peeking Iterator
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.
Hint:
- Think of "Looking ahead". You want to cache the next element.
- is one variable sufficient? Why or?
- Test your design with call order of
peek() before next() vs next() before peek() .
- For a clean implementation, check out Google's guava library source code.
Follow Up:how would you extend your design to is generic and work with all types, not just integer?
https://leetcode.com/problems/peeking-iterator/
Add a peek method to the iterator. Relatively simple, open a variable to save a next value, maintain the variable is OK.
1 //Java Iterator Interface Reference:2 //https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html3 classPeekingiteratorImplementsIterator<integer> {4 5 PrivateIterator<integer>it;6 Private Booleanpeeked =false;7 PrivateInteger top;8 9 PublicPeekingiterator (iterator<integer>iterator) {Ten //Initialize any member here. One This. it =iterator; A } - - //Returns the next element in the iteration without advancing the iterator. the PublicInteger Peek () { - if(!peeked) { -top =It.next (); -peeked =true; + } - returntop; + } A at //Hasnext () and next () should behave the same as in the Iterator interface. - //Override them if needed. - @Override - PublicInteger Next () { - if(!peeked) { - returnIt.next (); in}Else{ -peeked =false; to returntop; + } - } the * @Override $ Public BooleanHasnext () {Panax Notoginseng if(peeked) { - return true; the}Else{ + returnIt.hasnext (); A } the } + -}
[Leetcode] [Java] Peeking Iterator