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.
Thinking of solving problems
A variable is used to hold the value of the Peek element, next()
and peek()
The value is updated each time it is called and.
Implementation code
Java:
//runtime:120 MS//java Iterator Interface Reference://https://docs.oracle.com/javase/8/docs/api/java/util/iterator.html class peekingiterator implements Iterator<Integer> {Integer peek =NULL;PrivateIterator<integer> Iterator; PublicPeekingiterator (iterator<integer> Iterator) { This. iterator = iterator; }//Returns the next element in the iteration without advancing the iterator. PublicInteger Peek () {if(Peek = =NULL) {peek = Iterator.next (); }returnPeek }//Hasnext () and next () should behave the same as in the Iterator interface. //Override them if needed.@Override PublicInteger Next () {if(Peek = =NULL) {returnIterator.next (); }Else{Integer temp = peek; Peek =NULL;returnTemp }} @Override Public BooleanHasnext () {if(Peek! =NULL) {return true; }Else{returnIterator.hasnext (); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Peeking Iterator