zoukankan      html  css  js  c++  java
  • 284. Peeking Iterator 光是看看下一个值的遍历

    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().

    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.

    首先纠正一下英语:peek 看,peak 峰值

    思路:不太知道只看不取的peek怎么实现,一个思路:缓存啊!

    不知道 next()里面写什么:不就是iterator.next()就行了么?起码把成员变量(object变量,区别于类变量)定义好啊。还可以更新一下cache,变成下一个元素。

    class PeekingIterator implements Iterator<Integer> {
        Integer cache = null;
        Iterator<Integer> it;
        
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
            this.it = iterator;
            cache = it.next();  
        }
        
        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            //不太知道怎么实现,一个思路:缓存啊!
            return cache;
        }
        
        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            //这里还用我写么?不就是iterator.next()就行了么?起码把成员变量定义好啊
            int temp = cache;
            
            //更新一下cache,变成下一个元素
            cache = it.hasNext() ? it.next() : null;
            
            return temp;
        }
        
        @Override
        public boolean hasNext() {
            //
            return (cache != null);
        }
    }
    View Code
    
    
    



  • 相关阅读:
    10 款最佳剪贴板管理器
    悉数美剧《黑客军团》中的黑客工具
    Vim的使用方法
    Mysql跨平台(Windows,Linux,Mac)使用与安装
    Linux下网络故障诊断
    RHEL6.2下挂载光驱安装软件
    MySQL数据库服务器的架设
    Unix如何轻松快速复制
    【Linux基础】Linux常用命令汇总
    博客编号数字密码
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13659907.html
Copyright © 2011-2022 走看看