zoukankan      html  css  js  c++  java
  • LeetCode——Peeking Iterator

    Description:

    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.Show More Hint 

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

    Credits:
    Special thanks to @porker2008 for adding this problem and creating all test cases.

    就是利用Java中的Iterator接口来实现一个类,主要是peek()方法的实现与API中的不同,可以在peek()和next()中同时使用Iterator.next()来实现。

    设置一个top来保存当前值。

     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     
     7     private Integer top = null;
     8 
     9     public PeekingIterator(Iterator<Integer> iterator) {
    10         // initialize any member here.
    11         it = iterator;
    12     }
    13 
    14     // Returns the next element in the iteration without advancing the iterator.
    15     public Integer peek() {
    16         Integer peek;
    17         if(top != null) {
    18             peek = top;
    19         }
    20         else {
    21             peek = top = next();
    22         }
    23         return peek;
    24     }
    25 
    26     // hasNext() and next() should behave the same as in the Iterator interface.
    27     // Override them if needed.
    28     @Override
    29     public Integer next() {
    30         Integer next = 0;
    31         if(top != null) {
    32             next = top;
    33             top = null;
    34         }
    35         else {
    36             next = it.next();
    37         }
    38         return next;
    39     }
    40 
    41     @Override
    42     public boolean hasNext() {
    43         if(top != null) {
    44             return true;
    45         }
    46         return it.hasNext();
    47     }
    48 }
  • 相关阅读:
    无法在 Web 服务器上启动调试。调试失败,因为没有启用集成 Windows 身份验证。请
    .NET连接各种数据库的字符串
    修改远程桌面端口
    c#获取计算机信息
    ASP.NET 对路径的访问被拒绝
    关于.net 2.0数据库连接出错的一些经验
    Rose启动提示"java.lang.ClassNotFoundException"的解决
    Ext中的get、getDom、getCmp、getBody、getDoc的区别
    action中生成验证码图片
    extjs表格控件
  • 原文地址:https://www.cnblogs.com/wxisme/p/4873015.html
Copyright © 2011-2022 走看看