Description:
Given an Iterator class interface with methods: next()
hasNext()
and, design and implement a Peekingiterator c3/> 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. Show more Hint
Follow Up:how would you extend your design to is generic and work with all types, not just integer?
Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.
is to use the iterator interface in Java to implement a class, mainly the implementation of the Peek () method differs from the API, which can be implemented in both peek () and next () using Iterator.next ().
Set a top to save the current value.
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 7 PrivateInteger top =NULL;8 9 PublicPeekingiterator (iterator<integer>iterator) {Ten //Initialize any member here. Oneit =iterator; A } - - //Returns the next element in the iteration without advancing the iterator. the PublicInteger Peek () { - Integer Peek; - if(Top! =NULL) { -Peek =top; + } - Else { +Peek = top =next (); A } at returnPeek; - } - - //Hasnext () and next () should behave the same as in the Iterator interface. - //Override them if needed. - @Override in PublicInteger Next () { -Integer Next = 0; to if(Top! =NULL) { +Next =top; -top =NULL; the } * Else { $Next =It.next ();Panax Notoginseng } - returnNext; the } + A @Override the Public BooleanHasnext () { + if(Top! =NULL) { - return true; $ } $ returnIt.hasnext (); - } -}
Leetcode--peeking Iterator