• 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.

     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    peeked = false;
    24 }
    25 
    26     // Returns the next element in the iteration without advancing the iterator.
    27 int peek() {
    28         if(!peeked){ //has not visited the next item
    29             peeked = true;
    30             current = Iterator::next(); //store the value to facilitate the next()
    31         }
    32         return current;
    33 }
    34 
    35 // hasNext() and next() should behave the same as in the Iterator interface.
    36 // Override them if needed.
    37 int next() {
    38    if(!peeked) return Iterator::next();
    39    peeked = false;
    40    return current;
    41 }
    42 
    43 bool hasNext() const {
    44    return peeked || Iterator::hasNext();
    45 }
    46 private: 
    47     //Iterator ite;   
    48     bool peeked;
    49     int current;
    50 };
  • 相关阅读:
    Silverlight 数据绑定 (1):怎样实现数据绑定
    DynamicPopulateExtender 控件调 WebService 的500错误
    [翻译]Linq 的 7 个技巧简化程序操作
    [Silverlight] 一个易犯的错误:关于调用 WCF 服务
    Silverlight 数据绑定 (2):Source to Target
    KB kb KB大小写
    C# winform 程序中响应键盘事件
    异常“企图释放并非呼叫方所拥有的多用户终端运行程序”的处理
    php完美截取中文字符函数mb_substr
    php面试题(三)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4850616.html
Copyright © 2020-2023  润新知