Simple java solution using Stack


  • 0
    C
    class PeekingIterator implements Iterator<Integer> {
    
        Stack<Integer> stack = new Stack<Integer>();
        Iterator<Integer> it;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    it = iterator;
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
    	    if(stack.isEmpty()){
                int a = it.next();
                stack.push(a);
    	    }
    	    return stack.peek();
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next() {
    	    if(!stack.isEmpty()){
    	        return stack.pop();
    	    }else{
    	        return it.next();
    	    }
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return !stack.isEmpty()||it.hasNext();
    	}
    }
    

Log in to reply
 

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