zoukankan      html  css  js  c++  java
  • [LeetCode][Java]Peeking Iterator

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


    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.

    Hint:

    1. Think of "looking ahead". You want to cache the next element.
    2. Is one variable sufficient? Why or why not?
    3. Test your design with call order of peek() before next() vs next() before peek().
    4. For a clean implementation, check out Google's guava library source code.

    Follow up: How would you extend your design to be generic and work with all types, not just integer?

    https://leetcode.com/problems/peeking-iterator/


     
     
     
    给Iterator增加一个peek方法。
    比较简单,开一个变量存一个next的值,维护好这个变量就行了。
     1 //Java Iterator interface reference:
     2 //https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
     3 class PeekingIterator implements Iterator<Integer> {
     4 
     5     private Iterator<Integer> it;
     6     private boolean peeked = false;
     7     private Integer top; 
     8 
     9     public PeekingIterator(Iterator<Integer> iterator) {
    10         // initialize any member here.
    11         this.it = iterator;
    12     }
    13 
    14  // Returns the next element in the iteration without advancing the iterator.
    15     public Integer peek() {
    16         if(!peeked){
    17             top = it.next();
    18             peeked = true;
    19         }
    20         return top;
    21     }
    22 
    23     // hasNext() and next() should behave the same as in the Iterator interface.
    24     // Override them if needed.
    25     @Override
    26     public Integer next() {
    27         if(!peeked){
    28             return it.next();
    29         }else{
    30             peeked = false;
    31             return top;
    32         }
    33     }
    34 
    35     @Override
    36     public boolean hasNext() {
    37         if(peeked){
    38             return true;
    39         }else{
    40             return it.hasNext();
    41         }
    42     }
    43     
    44 }
     
     
  • 相关阅读:
    IOS应用内嵌cocos2dx游戏项目
    C++ 动态内存
    C++ 文件和流
    【转】SQL中的锁、脏读、不可重复的读及虚读
    【转】WCF扩展系列
    【转】WCF设置拦截器捕捉到request和reply消息
    关于拦截器模式的理解
    【转】netty源码分析之LengthFieldBasedFrameDecoder
    【转】使用nginx搭建高可用,高并发的wcf集群
    【转】Nginx 反向代理 负载均衡 虚拟主机配置
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4842205.html
Copyright © 2011-2022 走看看