zoukankan      html  css  js  c++  java
  • [LeetCode]284. Peeking Iterator(C++,类,暴力)

    题目链接:https://leetcode.com/problems/peeking-iterator/#/description

    题意:实现个迭代器。

    PeekingIterator是由Iterator继承来的,那么可以直接使用父类的hasNext和next。

    关键是如何实现peek了,如何才能不迭代下去,但是可以看下一个值?

    复制一下当前迭代器额。。。

     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     }
    24 
    25     // Returns the next element in the iteration without advancing the iterator.
    26     int peek() {
    27         PeekingIterator it = *this;
    28         return it.next();
    29     }
    30 
    31     // hasNext() and next() should behave the same as in the Iterator interface.
    32     // Override them if needed.
    33     int next() {
    34         return Iterator::next();
    35     }
    36 
    37     bool hasNext() const {
    38         return Iterator::hasNext();
    39     }
    40 };
  • 相关阅读:
    C语言练习之计算某年日是该年的第几天
    C语言练习之 猴子吃桃问题
    C语言练习之 求阶乘
    C语言学习(四)
    C语言学习(三)
    C语言学习(二)
    C语言学习(一)
    自定义函数汇总
    #2019121200026 最大子序列和
    #2019121000025-LGTD
  • 原文地址:https://www.cnblogs.com/kirai/p/6550753.html
Copyright © 2011-2022 走看看