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 }
     
     
  • 相关阅读:
    开学考试学生成绩管理Java
    动手动脑问题1
    数据库的链接错误分析
    ASP.NET自定义错误页面
    php declare
    HTTP运行期与页面执行模型
    分部类(Partial Classes)
    ASP.NET:小编浅谈泛型的使用
    Windows 2003 SP2下安装IIS无法复制文件
    php 的include require 区别
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4842205.html
Copyright © 2011-2022 走看看