zoukankan      html  css  js  c++  java
  • [Leetcode] Peeking Iterator, Solution

    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.

    [Thoughts]
    链表的一道设计题。next其实在这里就是获取头元素的值,并移动到下一个元素。peek在这里就是返回当前元素的值。

    [Code]
    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: class PeekingIterator : public Iterator {
    16: public:
    17: PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    18: // Initialize any member here.
    19: // **DO NOT** save a copy of nums and manipulate it directly.
    20: // You should only use the Iterator interface methods.
    21: this->length = nums.size();
    22: this->nums = &nums;
    23: }
    24: // Returns the next element in the iteration without advancing the iterator.
    25: int peek() {
    26: if(currentIndex < length) {
    27: return (*this->nums)[currentIndex];
    28: }
    29: return -1;
    30: }
    31: // hasNext() and next() should behave the same as in the Iterator interface.
    32: // Override them if needed.
    33: int next() {
    34: if(currentIndex < length) {
    35: currentIndex ++;
    36: return (*this->nums)[currentIndex-1];
    37: }
    38: return -1;
    39: }
    40: bool hasNext() const {
    41: return currentIndex < length;
    42: }
    43: private:
    44: int currentIndex = 0;
    45: int length = 0;
    46: const vector<int>* nums = NULL;
    47: };

    github:https://github.com/codingtmd/leetcode/blob/master/src/Peeking_Iterator.cpp


  • 相关阅读:
    log4j 使用笔记整理中
    执行bat文件
    excel让每个单元格的宽度随着字体自动变动的两种方式(有更好方法的大神,请忽略,求评论下)
    XML中CDATA及其字符实体的使用
    Java文件读写操作指定编码方式。。。。。
    尾数为0零BigDecimal不能装成正常数
    jquery 自动补全控件(支持IE6)待整理
    $.ajax提交,后台接受到的值总是乱码?明天再总结
    js定义变量需赋予初始值
    存储过程的优缺点
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078840.html
Copyright © 2011-2022 走看看