284. Peeking Iterator

3/20/2018 update:
In this problem we don't update next in hasNext(). hasNext just prepares next but not move the iterator to next. In the flatten next list iterator, hasNext() prepares for the stack, but next() is the one that actually pop the stack.

3/17/2018 update:
need to consider peek() return null. Add throw exception.


Analysis:
Use Integer next to cache the to be peeked element.


 // Java Iterator interface reference:  
 // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html  
 class PeekingIterator implements Iterator<Integer> {  
   Integer next = null;  
   Iterator<Integer> it = null;  
      public PeekingIterator(Iterator<Integer> iterator) {  
        // initialize any member here.  
        it = iterator;  
     if (it.hasNext()) {  
       next = it.next();  
     }  
      }  
   // Returns the next element in the iteration without advancing the iterator.  
      public Integer peek() {  
     return next;  
      }  
      // hasNext() and next() should behave the same as in the Iterator interface.  
      // Override them if needed.  
      @Override  
      public Integer next() {  
        Integer res = next;  
        next = it.hasNext() == true ? it.next() : null;  
        return res;  
      }  
      @Override  
      public boolean hasNext() {  
       return next != null;  
      }  
 }  
Since next has been initialize in the constructor, so the input iterator's hasNext() is no longer accurate for PeekingIterator. The next() method here is similar to the hasNext() method in Flatten iterator, it prepares the value to be peeked as flastten iterator's hasNext() method prepares the next() value.

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array