Simple Java Solution


  • 0
    M
    // Java Iterator interface reference:
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {
    
        int currentIndex = 0;
        Iterator<Integer> iterator;
        List<Integer> list = new ArrayList<>();
    	public PeekingIterator(Iterator<Integer> iterator)
    	{
    	    // initialize any member here.
    	    while( iterator.hasNext() )
    	        list.add(iterator.next());
    	    this.iterator = list.iterator();
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek()
    	{
                return list.get(currentIndex);
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next()
    	{
                this.currentIndex += 1;
                return iterator.next();
    	}
    
    	@Override
    	public boolean hasNext()
    	{
    	    return iterator.hasNext();
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.