Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

< Previous                  Next >

284. Peeking Iterator (Medium)

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().


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.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

Related Topics


Similar Questions

  1. Binary Search Tree Iterator (Medium)
  2. Flatten 2D Vector (Medium)
  3. Zigzag Iterator (Medium)


Hint 1 Think of "looking ahead". You want to cache the next element.
Hint 2 Is one variable sufficient? Why or why not?
Hint 3 Test your design with call order of peek() before next() vs next() before peek().
Hint 4 For a clean implementation, check out Google's guava library source code.
You can’t perform that action at this time.