java cache version


  • 0
    Y

    The idea is to maintain a cache to save the value that already be removed from the iterator.
    So when we call next(), we will first to get value from cache. If not cached. we call the iterator's next()

        private int cachedValue;
        private boolean cached = false; // when peek is called, the value will be cached
       
        private Iterator<Integer> iterator = null;
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
            this.iterator = iterator;
        }
    
        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            if (cached) return cachedValue;
            if (iterator.hasNext()) {
                cached = true;
                cachedValue = iterator.next();
                return cachedValue;
            }
            return null;
        }
    
        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            if (cached) {   // get from cache
                cached = false;
                return cachedValue;
            }
            else {
                if (iterator.hasNext()) return iterator.next();
                return null;
            }
        }
    
        @Override
        public boolean hasNext() {
            if (cached) return true;
            else return iterator.hasNext();
        }
    

Log in to reply
 

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