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.

    思路:缓存就是temp = cache, 改变cache,返回temp

    初始化:
    //相同的iterator,就用this来指明一下
    this.it = iterator;
    
    

    //cache也需要初始化成it.next()

    cache = it.next(); 
    class PeekingIterator implements Iterator<Integer> {
        Integer cache = null;
        Iterator<Integer> it;
        
        public PeekingIterator(Iterator<Integer> iterator) {
            //相同的iterator,就用this来指明一下
            this.it = iterator;
            //cache也需要初始化
            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
     
  • 相关阅读:
    FI关于凭证的修改和冲销操作
    abapAbout ABAP Debugger
    sd如何控制定价条件根据用户不同而操作不同(有的可以输入有的不可以)
    七种场景下的软件工作量估算步骤
    MMPP物料替换
    abap一个功能非常全面的增强出口查找工具 (仅供学习)
    BASISMonitoring in SAP Event Management
    2018GDKOI游记
    点击出现webQQ
    TCP/IP协议栈的基本工作原理
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13737548.html
Copyright © 2011-2022 走看看