zoukankan      html  css  js  c++  java
  • Peeking Iterator 解答

    Question

    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.

    Solution

    Key to the solution is to cache status and value ahead.

     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     private Iterator<Integer> iterator;
     5     private int current;
     6     private int peekValue;
     7     private boolean hasNext;
     8 
     9     public PeekingIterator(Iterator<Integer> iterator) {
    10         // initialize any member here.
    11         this.iterator = iterator;
    12         hasNext = this.iterator.hasNext();
    13         if (hasNext)
    14             peekValue = this.iterator.next();
    15     }
    16 
    17     // Returns the next element in the iteration without advancing the iterator.
    18     public Integer peek() {
    19         return peekValue;
    20     }
    21 
    22     // hasNext() and next() should behave the same as in the Iterator interface.
    23     // Override them if needed.
    24     @Override
    25     public Integer next() {
    26         current = peekValue;
    27         hasNext = iterator.hasNext();
    28         // Note here we need check hasNext, otherwise it will report runtime error
    29         if (hasNext)
    30             peekValue = iterator.next();
    31         return current;
    32     }
    33 
    34     @Override
    35     public boolean hasNext() {
    36         return hasNext;
    37     }
    38 }
  • 相关阅读:
    linux文件属性基础篇
    Linux重定向符号(重点)
    linux---vim和grep
    linux目录文件与系统启动(3)/usr目录、/var目录和/proc目录讲解
    Linux 安装和 连接xshell
    shiro 快速入门详解。
    th 表达式的简单使用。
    springboot 分布式项目,子级项目各自的作用。
    springboot 配置百里香 thymeleaf?
    springboot 配置mybatis 配置mapper.xml
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4860311.html
Copyright © 2011-2022 走看看