Runtime Error


  • 0
    R

    I am getting a Runtime Error with my solution below. Can't really understand the input description that's shown. The code works fine for the test cases I tested for. Can someone see a flaw in this?

    Error shown:Last executed input:
    [1,2,3,4]
    [0,1,1,2,2,1,1,2,0,1,0,2,0]

    Code:


    Iterator<? extends T> iterator = null;

    T next = null;
    
    boolean hasPeeked;
    
    public PeekingIterator(Iterator<? extends T> iterator) {
        // initialize any member here.
        this.iterator = iterator;
    
    }
    
    // Returns the next element in the iteration without advancing the iterator.
    public T peek() {
        if(!hasPeeked){
            if(iterator.hasNext()){
                next = iterator.next();
                hasPeeked = true;
            }
            else
                return null;
    
        }
        return next;
    }
    
    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    @Override
    public T next() {
        if(hasPeeked){
            T temp = next;
            hasPeeked = false;
            return temp;
        }
        else{
            return iterator.hasNext()?iterator.next():null;
        }
    
    }
    
    @Override
    public boolean hasNext() {
        if(hasPeeked)
            return next != null;
        return iterator.hasNext();
    }
    


Log in to reply
 

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