`

Google Interview - Peek Iterator

 
阅读更多

Suppose you have a Iterator class with has_next() and get_next() methods.

Please design and implement a PeekIterator class as a wrapper of Iterator and provide a peek() method.

When calling peek(), the user will only get the current element without moving forward the iterator.

 

Note: For Java solution we will use JDK's Iterator class, so the methods would be hasNext() and next().

 

public class PeekIterator {
    Iterator it;
    Integer top;
    public PeekIterator(Iterator it) {
        this.it = it;
    }
    
    public int peek() {
        if(top == null)
            top = (Integer)it.next();
        return top;
    }
    
    public boolean has_next() {
        return top != null ? true : it.hasNext();
    }
    
    public int get_next() {
        Integer val = top;
        if(val == null) 
            val = (Integer)it.next();
        top = null;
        return val;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics