Monday, December 14, 2015

Peeking Iterator

Q:

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek()operation -- it essentially peek() at the element that will be returned by the next call to next().

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].
Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.
Show Hint 

    A:
    就是保存当前的值。   为了得到这个值,需要用原本的next()。 这样, 原本的next()就要指向下下一个。  (similarly to   hasNext()  )
    // Java Iterator interface reference:
    // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
    class PeekingIterator implements Iterator<Integer> {
        private Integer curVal = null;
        private Iterator<Integer> iterator = null;
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
            this.iterator = iterator;
            this.next();
        }
    
        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            return curVal;
        }
    
        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            Integer res =  curVal;
            curVal = iterator.hasNext()?iterator.next() : null;
            return res;
        }
    
        @Override
        public boolean hasNext() {
            return curVal != null;
        }
    }
    
    Google Guava是用了isPeeked 的boolean值来表示,如果没有,就正常next()。 否则不调用next(). 转而直接给出原本的位置,即可.





    Mistakes:


    1. 没有保存 constructor中传进来的iterator   (一开始都去调用super了)
    2. 一开始,看了Hint,因此多用了一个变量记录是否到达end





    No comments:

    Post a Comment