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


  • 相关阅读:
    3.学习SpringMVC注解深入
    1.Google Blockly概述以及入门
    4.Servlet的Response和Request
    3.Servlet的ServletContext对象
    提高网络点击率的八种方法
    JNDI知道这么多就够了!
    jetty源代码剖析
    cocos2d-x 源代码分析 : control 源代码分析 ( 控制类组件 controlButton)
    Codeforces Round #254 (Div. 2)B. DZY Loves Chemistry
    几款“理想”“习惯”应用体验报告
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078840.html
Copyright © 2011-2022 走看看