zoukankan      html  css  js  c++  java
  • LeetCode OJ:Peeking Iterator(peeking 迭代器)

    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.

    Peeking迭代器,题目不再赘述,代码如下:

     1 // Below is the interface for Iterator, which is already defined for you.
     2 // **DO NOT** modify the interface for Iterator.
     3 class Iterator {
     4     struct Data;
     5     Data* data;
     6 public:
     7     Iterator(const vector<int>& nums);
     8     Iterator(const Iterator& iter);
     9     virtual ~Iterator();
    10     // Returns the next element in the iteration.
    11     int next();
    12     // Returns true if the iteration has more elements.
    13     bool hasNext() const;
    14 };
    15 
    16 
    17 class PeekingIterator : public Iterator {
    18 public:
    19     PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    20         // Initialize any member here.
    21         // **DO NOT** save a copy of nums and manipulate it directly.
    22         // You should only use the Iterator interface methods.
    23         this->next();
    24     }
    25 
    26     // Returns the next element in the iteration without advancing the iterator.
    27     int peek() {
    28         return nextVal;
    29     }
    30 
    31     // hasNext() and next() should behave the same as in the Iterator interface.
    32     // Override them if needed.
    33     int next() {
    34         int ret = nextVal;
    35         if(Iterator::hasNext()){
    36             bNext = true;
    37             nextVal = Iterator::next();
    38         }else{
    39             bNext = false;
    40         }
    41         return ret;
    42     }
    43 
    44     bool hasNext() const {
    45         return bNext;
    46     }
    47 private:
    48     bool bNext;
    49     int nextVal;
    50 };
  • 相关阅读:
    The network bridge on device VMnet0 is not running
    QuickContactBadge去掉三角
    在Android Studio中调用so中的方法
    Android Studio动态调试smali代码
    用AndroidStudio创建so
    Android逆向 破解第一个Android程序
    Java配置----JDK开发环境搭建及环境变量配置
    AndroidKiller报.smali文件丢失问题解决(关闭Android Studio的Instant Run)
    Android逆向 Android平台虚拟机
    Android逆向 APK文件组成
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5014552.html
Copyright © 2011-2022 走看看